ts-例子
1.利用具体参数的值决定展示额外的参数b或者c
泛型:
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
|
type Type = 'a' | 'b'
interface Func { <T extends Type>(props: T extends 'a' ? {type: T, b: number}: {type:T, c: number}): void; }
interface Func { <T extends 'a'>({ type, b }: { type: T; b: number }): void; <T extends 'b'>({ type, c }: { type: T; c: number }): void; }
const myFunc: Func = (props) => { console.log(props.type); };
myFunc({ type: 'b', c: 123});
|
联合类型:
1 2 3 4 5 6 7 8 9 10
| type aa = {type: 'a', b: number} | {type: 'b', c: number}
const myFunc1 = (props: aa) => { console.log(props.type); }; 1
myFunc1({ type: 'd', b: 123});
|