【发布时间】:2018-05-30 07:01:40
【问题描述】:
在打字稿中,可以使用泛型添加属性键吗?
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
有什么想法吗?这不可能吗?
【问题讨论】:
标签: typescript