//type annotations
let a : string, b : any;
//literal types
let dog = { id: 1 } // {id : number}
//type alias --> name for any type
type User = { id: number; }
//interface --> like type alias but extensible
interface Influencer extends User {
budget: number;
}
//nullish are considered subtypes of all types
let a : number = null
//never fields
type Tree = {flesh: never}
//functions
let getFavoriteNumber : () => Promise<number> =
async () => 28;
//Optional & Default params
function fn(x? : number = 10) {}
//read-only.
type User = { id : readonly string }
//unknown -- to be asserted later
let s : unknown ; s = 33
//enums -- named constants
enum UI { React; Vue; Angular; }
let z = UI.Angular // 2
Type assertions to convert less specific to more specific type
let x = y as string;
ele!.focus() //non-null assertion
Intersection types (formed by comining types)
type Cat = { name : string}; type Domestic = {owner : string}
let kitty : Cat & Domestic
Union types : can be one of any operand types. We can refine them with type narrowing
let x : boolean | string
tuple
typed array with a pre-defined length and types for each index.
let p : [string, number]
const
tells compiler to infer most narrow type
let k = 2, v = true; // number, boolean
let z = [k, v] as const //[2, true]
declare
specifies a type to an already existing variable
declare function foo(x : number) : string ;
Generics : create reusable types
interface Addfn<T, U, X> {
(x : T, y: U) : X
}
Namespace : to encapsulate types of functions, classes and objects that share common relationships.
declare namespace D3 {
export interface drawRect(x: number, y: number) : void;
//export is needed to access it outside
}
//usage
class Rectangle implements D3.drawRect {}