-
Notifications
You must be signed in to change notification settings - Fork 0
/
type-programming-exercise.ts
43 lines (31 loc) · 1.25 KB
/
type-programming-exercise.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import React from 'react';
// 练习1,实现 `defaultProps` 的类型 `InexactPartial<P>`
type InexactPartial<P> = {[K in keyof P]?: P[K]};
type FunctionComponent<P = {}> = {
(props: P): React.ReactNode;
defaultProps?: InexactPartial<P>;
};
type MyComponentProps = {
a: string;
b: number;
};
const MyComponent = (props: MyComponentProps) => {
return JSON.stringify(props);
};
MyComponent.defaultProps = {
a: 'default a',
c: false,
};
type MyComponentDefaultProps = InexactPartial<MyComponentProps>;
// 练习2,实现 `Defaultize<P, D>` 获取合并后的Props
type Defaultize<P, D> = unknown;
export type ExternalProps = Defaultize<MyComponentProps, typeof MyComponent.defaultProps>
type PropA = ExternalProps['a']; // string | undefined
type PropB = ExternalProps['b']; // number
type PropC = ExternalProps['c']; // boolean | undefined
// 练习3. 实现 `ComponentProps<Component>` 获取组件最终对消费方暴露的Props
type ComponentProps<C extends FunctionComponent<any>> = unknown;
export type ExternalProps2 = ComponentProps<typeof MyComponent>;
type ExternalPropA = ExternalProps['a']; // string | undefined
type ExternalPropB = ExternalProps['b']; // number
type ExternalPropC = ExternalProps['c']; // boolean | undefined