有没有一种方法可以将类型声明中特定键的值用作该相同声明(在Typescript中)中另一个键的类型? [英] Is there a way to use the value from a specific key in a type declaration as the type of another key in that same declaration (in Typescript)?

查看:94
本文介绍了有没有一种方法可以将类型声明中特定键的值用作该相同声明(在Typescript中)中另一个键的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在尝试创建一个采用 type 键的Variable类型,该键的类型为 string :有没有一种方法可以从称为 type 的键,并将其用作该类型声明中另一个键的类型?(不使用通用类型)

Let's say I'm trying to create a Variable type that takes a type key which has a type of string: is there a way to access the value from the key called type and use that as the type for another key in that type declaration? (Without using Generic Types)

例如,

type Variable = {
  name: string;
  required: boolean;
  type: string;
  defaultValue: Variable["type"];
}

const newWorkingVar: Variable = {
  name: "count",
  required: true,
  type: "number",
  defaultValue: 22 // This should work
}

const newErrorVar: Variable = {
  name: "count",
  required: true,
  type: "number",
  defaultValue: "test" // This should error
}

推荐答案

此答案与@LindaPaiste的答案类似,但有一个小的变化,即从名称到类型的映射保留在单独的类型中,然后对其进行操作以产生变量.例如,您的映射可能如下所示:

This answer is similar to @LindaPaiste's, with the minor change that the mapping from names to types is kept in a separate type, which is then manipulated to produce Variable. For example, your mapping could look like this:

type TypeMapping = {
  number: number;
  string: string;
  boolean: boolean
  // add more here as needed
}

然后变量可能是

type Variable = { [K in keyof TypeMapping]: {
  name: string;
  required: boolean;
  type: K;
  defaultValue: TypeMapping[K];
} }[keyof TypeMapping]

这是通过从 TypeMapping 中获取每个键 K 并将属性类型从 TypeMapping [K] 转换为的子类型来实现的该 K 的变量(其中 type 是键,而 defaultValue 是属性类型).生成的映射类型并不是我们想要的,因为它仍然具有与 TypeMapping 相同的键.通过对其进行索引.

This works by taking each key K from TypeMapping and transforming the property type from TypeMapping[K] to the subtype of Variable for that K (where type is the key and defaultValue is the property type). The resulting mapped type is not exactly what we want because it still has the same keys as TypeMapping. We get the union of its properties by indexing into it.

结果:

/* type Variable = {
    name: string;
    required: boolean;
    type: "string";
    defaultValue: string;
} | {
    name: string;
    required: boolean;
    type: "number";
    defaultValue: number;
} | {
    name: string;
    required: boolean;
    type: "boolean";
    defaultValue: boolean;
} */

现在您获得了想要的行为:

And now you get the behavior you're looking for:

const newWorkingVar: Variable = {
  name: "count",
  required: true,
  type: "number",
  defaultValue: 22 // okay
}

const newErrorVar: Variable = {
  name: "count",
  required: true,
  type: "number",
  defaultValue: "test" // error!
}

游乐场链接到代码

这篇关于有没有一种方法可以将类型声明中特定键的值用作该相同声明(在Typescript中)中另一个键的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆