我需要定义一个基于配置对象 ( anObject
) 的类型,它将在我的代码中使用。
我写了类似下面的东西,
const anObject = {
foo: ["a", "b", "c"],
bar: ["d", "e", "f"],
} as const;
type aType = {
key: keyof typeof anObject | "";
value: typeof anObject[keyof typeof anObject][number][];
} & (
| { key: ""; value: [] }
| { key: "foo"; value: typeof anObject["foo"][number][] }
| { key: "bar"; value: typeof anObject["bar"][number][] }
);
// aType =
// | { key: ""; value: [] }
// | { key: "foo"; value: ("a" | "b" | "c")[] }
// | { key: "bar"; value: ("d" | "e" | "f")[] };
const foo: aType = { key: "", value: [] };
但是我在上面的代码中遇到了两个问题。
每次向 中添加新密钥时anObject
,还需要向 中添加一行aType
TypeScript 无法识别中的空数组foo
并报告错误
Type 'never[]' is not assignable to type '("a" | "b" | "c" | "d" | "e" | "f")[] & []'.
aType
在 TypeScript 中声明的正确方法是什么?
值得在这里使用 union:
const anObject = {
foo: ["a", "b", "c"],
bar: ["d", "e", "f"],
} as const;
type AnObject = typeof anObject;
type Values<T> = T[keyof T]
type AType = {
[P in keyof AnObject]: {
key: P,
value: Array<AnObject[P][number]>
}
}
type Default = { key: ""; value: [] }
type Result = Values<AType> | Default
const foo: Result = { key: "", value: [] }; // ok
const bar: Result = { key: "bar", value: ["d"] } // ok
随意将任何新密钥添加到anObject
. 您无需在其他任何地方进行更新
请记住,正如@TJ Crowder 所说,value
物业没有订单。TS 将允许不同的值组合:[d,e] | [e, d] | [d]
.
如果你想要它的顺序相同,只需使用这一行:value: AnObject[P]
in AType
helper
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句