1. interface Person {
    2. name: string;
    3. age: number;
    4. walk: () => void;
    5. }
    6. interface bird {
    7. name: string,
    8. age: number;
    9. fly: () => void
    10. }
    11. // 提取出 name 和 age 作为必须属性
    12. // 非共有的fly 和 walk 作为非必须属性
    13. // TODO: 更好的做法,这写法太耦合了
    14. // export type Alien = Omit<Person, 'walk'> &
    15. // Omit<Bird, 'fly'> &
    16. // Partial<Pick<Person, 'walk'> & Pick<Bird, 'fly'>>;
    17. const aliesn: Alien[] = [
    18. {
    19. name: '111',
    20. age: 11,
    21. },
    22. {
    23. name: '222',
    24. age: 2,
    25. fly: () => {}
    26. },
    27. {
    28. name: '3333',
    29. age: 3,
    30. walk: () => {}
    31. },
    32. {
    33. name: '4444',
    34. age: 4,
    35. fly: () => {}
    36. walk: () => void;
    37. },
    38. ]
    1. // type Z = { id: number, age?: number } // 共有属性原样输出
    2. // type Z = { id: number }
    3. type PickerRequiedKeys<T> = {
    4. [K in keyof T]-?: {} extends Pick<T, K> ? never : K;
    5. }[keyof T]
    6. type PickCommonKeys<A, B> = {
    7. [K in keyof A & keyof B]: A[K] extends B[K]
    8. ? B[K] extends A[K]
    9. ? K
    10. : never
    11. : never
    12. }[keyof A & keyof B]
    13. type Z1 = Pick<X, PickCommonKeys<X, Y>>
    14. type Z2 = Pick<X, PickRequiredKeys<Pick<X, PickCommonKeys<X, Y>>>>
    1. interface Person {
    2. name: string,
    3. age: number;
    4. walk: () => void;
    5. }
    6. interface Bird {
    7. name: string,
    8. age: number;
    9. fly: () => void
    10. }
    11. export type Alien = Person | Bird
    12. // 赋值的时候没有问题
    13. const test: Alien = {
    14. name: 'asd',
    15. age: 12,
    16. walk: () => {},
    17. fly: () => {}
    18. }
    19. // 访问的时候报错
    20. // TS2339: Property 'walk' does not exist on type 'Alien'.
    21. // Property 'walk' does not exist on type 'Bird'.
    22. console.log(test.walk)
    23. // ts 无法判断是 bird 还是 person, 可以用 in 把类型搜索,让 ts 更好推断
    24. console.log('walk' in test ? test.walk() : test.fly())

    Promise 和 PromiseLike

    1. // the return type of an async function or method must be the global Promise<T> type.
    2. //Did you mean to write 'Promise<void>'?(1064)
    3. async function getUserInfo(user: string): PromiseLike<void> {
    4. return Promise.resolve(undefined);
    5. }
    6. //
    7. async function getUserInfo(user: string): Promise<void> {
    8. return Promise.resolve(undefined);
    9. }