interface Person {name: string;age: number;walk: () => void;}interface bird {name: string,age: number;fly: () => void}// 提取出 name 和 age 作为必须属性// 非共有的fly 和 walk 作为非必须属性// TODO: 更好的做法,这写法太耦合了// export type Alien = Omit<Person, 'walk'> &// Omit<Bird, 'fly'> &// Partial<Pick<Person, 'walk'> & Pick<Bird, 'fly'>>;const aliesn: Alien[] = [{name: '111',age: 11,},{name: '222',age: 2,fly: () => {}},{name: '3333',age: 3,walk: () => {}},{name: '4444',age: 4,fly: () => {}walk: () => void;},]
// type Z = { id: number, age?: number } // 共有属性原样输出// type Z = { id: number }type PickerRequiedKeys<T> = {[K in keyof T]-?: {} extends Pick<T, K> ? never : K;}[keyof T]type PickCommonKeys<A, B> = {[K in keyof A & keyof B]: A[K] extends B[K]? B[K] extends A[K]? K: never: never}[keyof A & keyof B]type Z1 = Pick<X, PickCommonKeys<X, Y>>type Z2 = Pick<X, PickRequiredKeys<Pick<X, PickCommonKeys<X, Y>>>>
interface Person {name: string,age: number;walk: () => void;}interface Bird {name: string,age: number;fly: () => void}export type Alien = Person | Bird// 赋值的时候没有问题const test: Alien = {name: 'asd',age: 12,walk: () => {},fly: () => {}}// 访问的时候报错// TS2339: Property 'walk' does not exist on type 'Alien'.// Property 'walk' does not exist on type 'Bird'.console.log(test.walk)// ts 无法判断是 bird 还是 person, 可以用 in 把类型搜索,让 ts 更好推断console.log('walk' in test ? test.walk() : test.fly())
Promise 和 PromiseLike
// the return type of an async function or method must be the global Promise<T> type.//Did you mean to write 'Promise<void>'?(1064)async function getUserInfo(user: string): PromiseLike<void> {return Promise.resolve(undefined);}//async function getUserInfo(user: string): Promise<void> {return Promise.resolve(undefined);}
