基础知识
基础类型: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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。