首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据现有的对象值定义Typescript对象类型?

如何根据现有的对象值定义Typescript对象类型?
EN

Stack Overflow用户
提问于 2020-10-10 22:14:06
回答 1查看 108关注 0票数 1
代码语言:javascript
复制
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
  }
}

基于上面的配置,我将向浏览器呈现一个表单,表单提交的预期输出对象应该如下所示:

代码语言:javascript
复制
{
  full_name: '',
  age: 0
}

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

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

代码语言:javascript
复制
type FormOutput = {
  [key in keyof typeof memberInfoKeys]: typeof InputTypeMapping[inputConfig[key].type]
}

有没有可能在Typescript中创建这样的类型?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-11 01:20:46

主要问题是由于我们不能从枚举中获得字符串文字联合类型的事实,正如所讨论的here

但是您可以通过在相同的问题here中使用const作为answer来实现相同的功能。

如果它对您有效,请检查此选项

代码语言:javascript
复制
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)

Playground

const断言上的More

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64294372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档