[英]use keyof in a mapped type to return an array of values in typescript
在 typescript 中,我可以創建一個類型安全的 object 鍵數組,如下所示:
export type Keys<T> = [keyof T][];
export const keys = <T>(o: T): Keys<T> => Object.keys(o) as any;
const k = keys(a);
但是我怎樣才能為這些值創建一個類似的類型:
export type Values<T> = [T][keyof T];
// Type 'keyof T' cannot be used to index type '[T]'.
您需要索引T
,而不是[T]
:
type Values<T> = T[keyof T][]; // or Array<T[keyof T]>
type Foo = { a: number, b: string };
type FooValues = Values<Foo>; // (string | number)[]
[T]
是具有單個T
元素的元組,因此您最初的嘗試是嘗試使用T
的鍵“索引”元組 - 因此出現錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.