假设有一个简单的对象类型X和一个函数来创建X,createXList的显式类型数组,如下所示:
type X = Readonly<{
a: string
b: string
}>
type XList = Readonly<X[]>
// TS workaround to create an explicitly-typed X
const createXList = <TXList extends XList>(xList: TXList): TXList => xList
*/然后可以创建一个显式类型的X数组,比如xList,如下所示:
const xList = createXList([
{ a: 'foo', b: 'bar' },
{ a: 'fizz', b: 'buzz' },
] as const)
/*
const xList: readonly [{
readonly a: "foo";
readonly b: "bar";
}, {
readonly a: "fizz";
readonly b: "buzz";
}]问题是:如何为字典创建一个类型,其中每个键都是a和b属性的连接,而值只是用于在字典中创建每个键的数组的值,同时仍然保持显式类型。例如:
type XListToXDict<T extends XList> = { /* some magic */ }
type Test = XListToXDict<typeof xList>
/*
{
"foobar": { a: "foo", b: "bar" };
"fizzbuzz": { a: "fizz", b: "buzz" };
}
*/因此,例如,为特定X创建键的类型是:
type XToKey<T extends X> = `${T['a']}${T['b']}`备注:
假设您至少可以进行以下操作来提取字典的键(使用上面的XToKey):
type XListToKeys<T extends XList> = XToKey<T[number]>但是这失败了,因为它生成了a和b的所有可能组合(在xList的特定情况下,即"foobar" | "foobuzz" | "fizzbar" | "fizzbuzz")。
然后,需要从数组中为字典中的每个值选择一个特定的项。
发布于 2022-05-30 17:27:59
您可以使用映射类型和用as重命名密钥名来实现这一点。
type XListToXDict<T extends XList> = {
[K in keyof T & `${bigint}` as T[K] extends { a: infer A, b: infer B }
? `${A & string}${B & string}`
: never
]: T[K]
}https://stackoverflow.com/questions/72437782
复制相似问题