题目描述
TypeScript 如何根据值定义类型?
相关代码
type InputProps = {
a: string;
};
type SelectProps = {
b: string;
};
type TypeProps = 'Input' | 'Select';
type ConfigProps = {
type: TypeProps;
componentProps: InputProps | SelectProps;
};
const config: ConfigProps = {
type: 'Input',
componentProps: { // 期望实现:如果type值为'Input',则componentProps只能是InputProps类型
a: 'demo'
}
};
你期待的结果
如上代码,该如何定义ConfigProps
才能实现动态根据type
值去确定componentProps
的类型呢?
可以这样
或者