首页 > 解决方案 > 如何按值定义类型?

问题描述

代码:

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: { 
    a: 'demo'
  }
};

如何定义ConfigProps,如果type道具值相等InputcomponentProps应该是 InputProps

预计:

const config: ConfigProps = {
  type: 'Input',
  componentProps: { 
    b: 'demo' // ERROR, because type equal to 'Input', but InputProps just allow prop a
  }
};

标签: javascripttypescripttypescript-typings

解决方案


您可以将您的类型定义为更明确的值:

type ConfigProps = {
  type: 'Input';
  componentProps: InputProps;
} | {
   type: 'Select';
   componentProps: SelectProps;
};

这种方式如果type'Input'那么componentProps必须是InputProps


推荐阅读