能夠使用 type 和 interface 來建立類型函數
聲明基本類型別名,聯合類型,元組等類型code
type S = string; type IFoo = IBar | string;
可以使用 typeof 獲取實例的類型賦值對象
const a:number = 1; const IA = typeof a; // IA 被 ts 識別爲 number
interface 可以聲明合併接口
interface IFoo { name:string } interface IFoo { age:number } // 等於 type IFoo = { name:string age:number }
以IFoo做爲例子get
interface IFoo { name:string age:number gender:string }
type IBar = IFoo['name'] // IBar = string
type IBar = Pick<IFoo, 'name'> // IBar = {name: string}
type IBar = Pick<IFoo, 'name' | 'age'> // IBar = {name: string, age: number}
type IBar = Omit<IFoo, 'name'> // IBar = {age: number, gender: string}
type IBar = keyof IFoo // IBar = "name" | "age" | "gender"
type IBar = IFoo[keyof IFoo] // IBar = string | number
type IBar = Record<'name' | 'age', string> // IBar = {name: string, age: string}
interface IFoo { name: string age: string gender: string getSkill(): void setSkill: (skill: string[]) => void } // 生成一個新類型,將 age 和 gender 的類型修改成 number,其餘的類型不變 // 使用上述知識 聲明一個新的高級類型IBar: type IBar<K extends string,T = number> = (Record<K, T> & Omit<IFoo, K>) type IBaz = IBar<'age' | 'gender'> // 生成新的類型 IBaz ,符合上述描述 // 而且使用 Ibar 可將 age 和 gender (或其餘)更改成任意其餘類型 如: type IBax = IBar<'age' | 'gender' | 'name', string[]>
interface IFoo { name: string age: number gender: string getSkill(): void // type 不支持此種聲明 setSkill: (skill: string[]) => void }
以此爲例子:string
type IFoo = (name: string, age: number) => { name: string, age: number, gender: string }
type IBar = Parameters<IFoo> // IBar = [string, number]
type IBar = ReturnType<IFoo> // IBar = {name: string, age: number, gender: string}