ts进阶

2020-10-27  本文已影响0人  看到这朵小fa了么

发现看完了文档还是不会写,别人写的代码又看不懂,找了篇文档看:https://blog.csdn.net/weixin_39843414/article/details/105108806
总结一下:

interface和type

// type可以表示更多类型,可以使用计算
type Name = string;
 
type PartialPointX = {x:number;};
type PartialPointY = {y:number;};
 
type PartialPoint = PartialPointX | PartialPointY;
 
type Data = [number,string,boolean];

// type继承interface
interface particalPerson {name: 'liming'}
type person = name & {age: 18}
// interface继承 type
type particalPerson = {name: 'liming'}
interface person extends particalPerson {age: 18}

// implements
interface Point {x: number, y:number}
class somePoint implements Point {x: 1, y: 2}
//error 联合类型无法被类实现
type Point2 = {x: number} | {y:number}
class somePoint2 implement Points {x: 1, y:2}

extends

type isEuqalType<A, B> = A extends B ? (B extends A ? true : false) : false

typeof

interface Izip {name: '', age: 12, class: 1}
type ant = typeof Izip // ant=name | age | calss

泛型

function plunk<T, K extends typeof T>(o: T, name: K[]): T[K][] {
  return name.map(n =>o(n))
}
interface Point = {name: string, age: number}
let person: Point = {name: 'liming', age: 10}
let result: string[] = plunk(person, ['name', 'name', 'name']) // 输出 ['liming', 'liming', 'liming']

工具函数

type Partial<T> = <P in  keyof T?: T[P]>
type Required<T> = <P in keyof T-?: T[P]>
type Readonly<T> = <readonly [P in keyof T]: T[P]>
type Record<K extends keyof any, T> = {<P in K: T>}
type Extract<T, K> =< T extends K?T : never>
type Exclude<T, K> = <T extends K? never: T>
type Pick<T, K extends keyof T> = {P in K: T[P]}
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>
上一篇 下一篇

猜你喜欢

热点阅读