gpt4 book ai didi

typescript - 将键值对接口(interface)列表转换为单个映射类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:51:01 24 4
gpt4 key购买 nike

我有一组这样的接口(interface):

interface Foo {
key: "fooKeyType",
value: "fooValueType",
}

interface Bar {
key: "barKeyType",
value: "barValueType",
}

interface Baz {
key: "bazKeyType",
value: "bazValueType",
}

type FooBarBaz = Foo | Bar | Baz;
type FooBarBazKey = FooBarBaz["key"];
type FooBarBazValue = FooBarBaz["value"];

其中 *keyType 始终是常量字符串(因此它们是有效键),但 *valueType 只是可能是实际类型(例如数字、日期、自定义类等)。

我想把这些接口(interface)转换成一个映射key->value的singular type map,比如下面这样:

/* Can I generate this from the above? */
type FooBarBazMap = {
fooKeyType: "fooValueType",
barKeyType: "barValueType",
bazKeyType: "bazValueType",
}

有没有办法用映射类型做到这一点?映射类型似乎不允许您引用当前索引的类型,只能引用整个类型,这意味着您不能将来自同一接口(interface)的字段绑定(bind)在一起。

最佳答案

是的。这一切都归结为转换这种类型:

type KeyValue<K extends string, V> = {
key: K,
value: V,
};

...为此:

type Desired<K extends string, V> = {
[key in K]: V;
};

理想情况下,我们希望输入如下内容:

type TransformKeyValueWrong<T extends KeyValue<T["key"], T["value"]>> = {
[key in T["key"]]: T["value"];
};

但是 typescript 编译器会对我们大喊“[ts] 类型参数 'key' 有一个循环约束。”这是真的,但不会阻止我们,因为我们有通用参数默认值!

type TransformKeyValue<T extends KeyValue<K, T["value"]>, K extends string = T["key"]> = {
[key in K]: T["value"];
};

我们现在要做的就是为 Foo、Bar、Baz 声明交集类型:

type SuperDuperType =
& TransformKeyValue<Foo>
& TransformKeyValue<Bar>
& TransformKeyValue<Baz>
;

验证它是否有效:

type Test = SuperDuperType["barKeyType"]; // type Test = "barValueType";

请注意,泛型参数默认值需要 TypeScript 版本 >=2.3

关于typescript - 将键值对接口(interface)列表转换为单个映射类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44578801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com