簡體   English   中英

在映射類型中使用 keyof 以返回 typescript 中的值數組

[英]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.

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