1
enum InputType {
  Text = 'text',
  Number = 'number'
}

type InputTypeMapping = {
  [InputType.Text]: string,
  [InputType.Number]: number
}

const inputConfig = {
  full_name: {
    label: 'Name',
    type: InputType.Text
  },
  age: {
    label: 'Age',
    type: InputType.Number
  }
}

基于上面的配置,我将一个表单渲染到浏览器,表单提交的预期输出对象应该是这样的:

{
  full_name: '',
  age: 0
}

我想根据上inputConfig一个片段中的对象为预期输出创建对象类型。每个键 ( keyof inputConfig) 应映射到适当的输入类型映射 ( typeof InputTypeMapping[inputConfig[key].type])。

我找不到创建这种类型的方法。预期的类型应该是这样的([key in keyof typeof memberInfoKeys]有效,但typeof InputTypeMapping[inputConfig[key].type]无效,只是为了给你一个我所期待的图片)

type FormOutput = {
  [key in keyof typeof memberInfoKeys]: typeof InputTypeMapping[inputConfig[key].type]
}

有没有可能在 Typescript 中创建这种类型的方法?

4

1 回答 1

1

出现主要问题是因为我们无法从这里讨论的枚举中获取字符串文字联合类型。

但是您可以通过const在同一问题中使用 as answer实现相同的目的。

检查它是否适合您

const InputType = {
  Text: "text",
  Number: "number",
} as const;

type InputTypeMapping = {
  [InputType.Text]: string,
  [InputType.Number]: number,
}

const inputConfig = {
  full_name: {
    label: 'Name',
    type: InputType.Text,
  },
  age: {
    label: 'Age',
    type: InputType.Number,
  },
}

type InputConfigType = typeof inputConfig

// type FormType = {
//     full_name: string;
//     age: number;
// }
type FormType = {
  [K in keyof InputConfigType]: InputTypeMapping[InputConfigType[K]['type']]
}



// explanation

// this gives type
// X = "number" | "text" 
// when `InputType` is a const
// and gives back `InputType` when `InputType` is an enum
type X = (typeof InputType)[keyof typeof InputType]

// to use the InputType as enum in a function or variable
type InputTypeKeys = (typeof InputType)[keyof typeof InputType]

let variable: InputTypeKeys = InputType.Number

function func(_a: InputTypeKeys) {
  // ...
}

func(InputType.Number)

操场

更多关于const断言

于 2020-10-10T17:20:46.043 回答