簡體   English   中英

Typescript - 如何獲取類型化數組?

[英]Typescript - How Do I Get A Typed Array?

我的示例用例。

type someEnum = 'a' | 'b';

const someObj: { [K in someEnum]: string } = {
    a: 'a',
    b: 'b',
};

const a: Array<someEnum> = ['a', 'b'];

// In Future update someEnum

type someEnum = 'a' | 'b' | 'c';

// Gives an error;

// Property 'c' is missing in type '{ a: string; b: string; }' 
// but required in type '{ a: string; b: string; c: string; }'.

const someObj: { [K in someEnum]: string } = {
    a: 'a',
    b: 'b',
};

// No error;
const a: Array<someEnum> = ['a', 'b'];

// Is There someThing like;

// const typedArray: [K in someEnum]

擁有這樣的功能真的很酷; 是否有一些功能可以實現相同的功能。 提前致謝。

使用一些變通方法將元組合並是很誘人的,請不要使用它

您可以通過多種方式解決此問題,最簡單的方法是如果枚舉在您的控制之下,則從數組而不是枚舉開始:

const allPosibilitieForSomeEnum = ['a',  'b' , 'c'] as const
type someEnum = typeof allPosibilitieForSomeEnum[number];

您可以改用對象並使用keys來獲取密鑰。

或者您可以使用驗證所有成員都存在的函數:

type someEnum = 'a' | 'b' | "c";

function checkEnum<TEnum>() {
    return function <TActual extends TEnum[]>(...p: TActual & ([TEnum] extends [TActual[number]] ? {} : {
        error: ["Array does not contain all members, expected: ", TEnum, "found:", TActual[number]]
    })) {
        return p
    }
}

const someObj =  checkEnum<someEnum>()("a", "b", "c") 
const someObj2 =  checkEnum<someEnum>()("a", "b") ///  Property 'error' is missing in type '["a", "b"]' but required in type '{ error: ["Array does not contain all members, expected: ", someEnum, "found:", "a" | "b"]; }'.

您想根據聯合類型創建一個元組。 這確實是可能的,但有點復雜。 TypeScript Github 存儲庫中還有一個問題可以解決這個問題。

那里的答案之一似乎工作得很好。 這是TypeScript Playground 中的示例。

暫無
暫無

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

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