Introduction TypeScript is a popular programming language that extends JavaScript by adding static types. Typescript catches errors at compile time rather than at runtime, making the code more reliable and easier to debug.
Syntax Primitive Data Types
number
boolean
string
object
undefined
null
Declare a Type For a Variable Define types of a variable using :
.
1 2 3 4 5 6 let name : string = "John" ;let age : number = 30 ;let isStudent : boolean = false ;let message : string [] = ["1" , "2" , "3" ];let message : Array <string > = ["1" , "2" , "3" ];
Define a Type 1 2 type Color = "Red" | "Green" | "Blue" ;let c : Color = "Red" ;
1 2 3 4 5 type myType = { myProperty : string ; };const newVariable : myType = {myProperty : "xxx" };
1 2 3 4 5 6 7 8 9 10 11 12 type User = { _id : string ; name : string ; is_admin?: boolean ; };const user : User = { _id : "555" ; name : "Eric" ; };export {User }
Denote optional params with ?
Typed Functions 1 2 3 const getComments = (id ) => { return []; }
1 2 3 const getComments = (id : string ): Comment [] => { return []; }
1 2 3 4 5 6 type CommentProps = { _id : string ; name : string ; handleAdd : () => void ; }