TypeScript 如何根据值定义动态类型?

题目描述

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的类型呢?

阅读 5.3k
1 个回答

可以这样

type InputProps = {
  a: string;
};

type SelectProps = {
  b: string;
};

type ComponentType = "Input" | "Select";

type ComponentProps = {
  Input: InputProps;
  Select: SelectProps;
};

type ConfigProps<T extends ComponentType = ComponentType> = {
  type: T;
  componentProps: ComponentProps[T];
};

const config: ConfigProps<"Select"> = {
  type: "Select",
  componentProps: {
    // 期望实现:如果type值为'Input',则componentProps只能是InputProps类型
    // a: "d",
    b: "a"
  }
};

或者

type InputProps = {
  a: string;
};

type SelectProps = {
  b: string;
};

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

const config: ConfigProps = {
  type: "Input",
  componentProps: {
    // 期望实现:如果type值为'Input',则componentProps只能是InputProps类型
    // a: "d",
    b: "a"
  }
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题