gpt4 book ai didi

typescript - 在 Typescript 中,可以使用泛型添加属性键吗?

转载 作者:行者123 更新时间:2023-12-02 09:12:27 25 4
gpt4 key购买 nike

在 typescript 中,可以使用泛型添加属性键吗?

function f<T extends string>(k: T) {
return { [k]: 'test'; };
}

const obj = f('foo');
// some how assert that obj.foo exists

我有一个类似上面的函数,它接受一个键 k 并使用 {[identifier]: 'value'} 将该键动态添加到一个对象中。


我想知道是否可以捕获字符串文字类型,例如'some-key'/T extends string 并在另一种类型中使用文字。像这样的:

interface F<T extends string> {
[T]: SomeRandomType;
otherKey: string;
anotherKey: number;
}

interface SomeRandomType { /* ... */ }

const f: F<'bar'> = /* ... */;
f.otherKey; // should work
f.anotherKey; // should work
f.bar; // should work

有什么想法吗?这不可能吗?

最佳答案

是的,这可以使用 mapped types 的创意组合来实现。和 intersection types .

您可以使用映射类型对“任意字符串文字键属性”的情况进行建模。

type F<Keys extends string> = {
[K in Keys] : number;
}

const f : F<'bar'> = null;
f.bar; // typed as a number
f.wibble; // type error

请注意,映射类型必须是 type 声明,而不是 interface。不要问我有什么区别!

然后是使用交集类型运算符 & 将附加属性分层的情况。出于某种原因,您必须为此使用 & 。您似乎不允许将这些属性声明为同一对象类型的一部分。

type F<Keys extends string> = {
[K in Keys] : number;
} & {
additionalKey1 : object;
additionalKey2 : string;
}
const f : F<'bar'> = null;
f.bar; // typed as a number
f.additionalKey1; // typed as an object

关于typescript - 在 Typescript 中,可以使用泛型添加属性键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50593983/

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