簡體   English   中英

在Typescript中,可以使用泛型添加屬性鍵嗎?

[英]In Typescript, it is possible to add properties keys using generics?

在打字稿中,可以使用泛型添加屬性鍵嗎?

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

有任何想法嗎? 這不可能嗎?

是的,這可以通過創造性地使用映射類型相交類型的組合來實現。

您可以使用映射類型對“任意字符串文字鍵屬性”案例進行建模。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM