问题描述
假设我正在尝试创建一个采用 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
相同的键.通过对其进行索引.
/* 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中)中另一个键的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!