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中创建这样的类型?
发布于 2020-10-11 01:20:46
主要问题是由于我们不能从枚举中获得字符串文字联合类型的事实,正如所讨论的here。
但是您可以通过在相同的问题here中使用const作为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断言上的More
https://stackoverflow.com/questions/64294372
复制相似问题