Typescript Notes Part 1
source from 01-07
type inference & variable declaration
when use let to declare variable, it will be inferred by typescript and with const, type will be exactly what you assign and if not assign any value, tpye will be inferred as any
let a = 5;
// a : number
const b = 6;
// b : 6
let c;
// c : any
Type annotation
We can add specific type to variable when declaration
// annotation
let a: string;
// if you set a to number, it will throw an error
a = 6; //ERROR
// => Type 'number' is not assignable to type 'string'
Objects
type ObjectType = {
key1: string,
key2: number,
key3?: string, // this one is optional with "?" operator
};
// nested Object type
type NestedObjectType = {
[key: string]: {
k1: string,
k2: number,
},
};
Array
type ArrayType = string[]; // => ["test","lol"]
Tuples
this is not in javascript, It need an explicitly type and order in array
type TupleType = [number, string];
Type checking
typescript's type system is static the difference between static and dynamic is type-checking is perfomed at compile time or runtime
Union and Intersection
// Union with "|" ,like OR
type UnionType = string | number;
// intersection with "&", like AND
type IntersectionType = { k1: string } & { k2: number };
// if you try to use intersection with two primitive types, you will get error
type TwoPrimitiveType = string & number; // => become never
let a: TwoPrimitiveType = 6; // Type 'number' is not assignable to type 'never'.
Type aliases and Interfaces
- Type alias basically it's what I did above like declaration of type easier to read, import and export need "=" operator
inheritance in type: use "&"
- Interface It can use to define an object type It's more like a class, no need "=" operator
inheritance in interface: use "extends" | "implements" "extends" and "implements" can use together at same time
//type
type TheType = {
key: string,
};
// also can use
type StringType = string;
//interface
interface InterfaceType {
key: string;
}
note that:
- type alias can not do a second declaration, while interface can in interfaces, it will merge all the declaration together
- If you need to define something other than object type, use type alias
- If you want other people can customized types, use interfaces
so far is part one from source I think this is very helpful to learn typescript I take this notes to help me memorize these knowledge If there are any wrong, please without hesitation to tell me 🙏
this is today's sharing 👋