![](/img/trans.png)
[英]Typescript - How to dynamically type an object with keys from a dynamic array of objects
[英]Get type inference from keys in a dynamic array in TypeScript
我正在尋找基於數組中鍵的值的類型推斷。
對於上下文,我正在研究 class ,您可以在其中傳入選項列表和默認值:
interface Option {
value: string;
}
interface SelectArgs {
options: Option[];
defaultValue: Option['value'];
}
class SelectConfig {
options: Option[];
defaultValue: Option['value'] // can I get the value options with autocompletion here?
constructor(args: SelectArgs ) {
Object.assign(this, args);
}
}
我將在 class 的上下文中使用它,例如,如果我實例化一個新的 class:
const select = new SelectOptions({
options: [{value: 'Hello'}, {value: 'World'}]
defaultValue: "Hello" // I want to give me type inference of either "Hello" | "World"
})
在這種情況下鍵入defaultValue
的最佳方法是什么,因此它始終是options
的傳入values
之一?
是的,它看起來像這樣,使用 class 的通用參數:
type Narrow<T> =
| (T extends infer U ? U : never)
| Extract<T, number | string | boolean | bigint | symbol | null | undefined | []>
| ([T] extends [[]] ? [] : { [K in keyof T]: Narrow<T[K]> });
class SelectConfig<Options extends Option[]> {
options!: Options;
defaultValue!: Options[number]['value']
constructor(args: {
options: Narrow<Options>;
defaultValue: Options[number]["value"]
}) {
Object.assign(this, args);
}
}
我選擇使用這種Narrow
實用程序類型,因此在創建 class 時不需要使用as const
。 我們將縮小給定選項的類型,然后將默認值的類型設置為選項中給定的任何值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.