基础知识
根底类型:number string boolean array object
-
enum 枚举
接口给前端返回一盒 status 字段enum ActivityStatus { NOT_START = 'notStart', STARTED = 'stated' } const status = ActivityStatus.NOT_START;
- type, interface
// type UserInfo = {
// name: string;
// height?: number
// }
interface UserInfo {
name: string;
height?: number
}
const userInfo = {name: 'cxx'}
- 联结类型 | (联结类型一次只能应用一种类型,而穿插类型每次都是多个合并类型)
- 穿插类型 & (联结类型一次只能应用一种类型,而穿插类型每次都是多个合并类型)
interface UserInfoA {
name?: string;
height?: number
}
interface UserInfoB {width: number}
function test (param: UserInfoA | UserInfoB){// ...}
-
typeof
typeof 'a' //string
function toArray(x: number):Array<number>{return {x}; } type Func = typeof toArray; // (x: number) => number[]
- keyof
// 能够用来获取一个对象中所有的 key 值
interface Person{
name: string;
age: number;
}
type KPerson = keyof Person; // 'name' | 'age'
-
in 用来遍历枚举类型
type Keys = 'a' | 'b' | 'c'; type obj = {[key in Keys]: any; }
-
extends 继承类型
interface TLength{length: number} function loggingIdentity<T extends TLength>(arg: T): T{console.log(arg.length); return arg; } loggingIdentity(3); loggingIdentity({length: 10, value: 3});
-
Paritial
Paritial<T> 的作用是将某个类型的属性全副变为可选项interface PageInfo{title: string;} type OptionalPageInfo = Paritial<PageInfo>;
- Required 全副变为必选项
-
Readonly 全副变为只读
interface PageInfo{title: string;} type ReadonlyPageInfo = Readonly<PageInfo>; const pageInfo: ReadonlyPageInfo = {title: 'cxx'}; pageInfo.title = 'ch'; // error
-
Record
Record<K extends keyof any, T> 将 K 中的所有属性的值转化为 T 类型interface PageInfo{title: string;} type Page = "home" | "about" | "contact"; const x: Record<Page, PageInfo> = {home: {title: '111'}, about: {title: '222'}, contact: {title: '333'}, }
-
Exclude
Exclude<T, U> 将某个类型中属于另一个的类型移除type T0 = Exclude<"a" | "b" |"c", "a"> // "b |"c"type T1 = Exclude<"a"|"b"|"c","a"|"b"> //"c"
-
Extract
Extract<T, U> 从 T 中提取 U,大略是取交加的意思type T0 = Extract<"a" | "b" |"c", "a" | "f"> // "a" type T1 = Extract<string | number | (() => void), Function> // () => void