簡體   English   中英

從 TypeScript 中的動態數組中的鍵獲取類型推斷

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

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