簡體   English   中英

擴展索引打字稿界面

[英]Extend indexed typescript interface

考慮一個簡單的索引接口:

interface FormData {
    [K: string]: string;
}

這個小家伙很好。 但是,在某些情況下,我想允許屬性為字符串數組。

interface AcmeFormData extends FormData {
    foobar: string[];
}

打字稿抱怨

類型“ string []”的屬性“ foobar”不可分配給字符串索引類型“ string”。

查看文檔,似乎以下內容應該可行,但也有抱怨。

interface FormData {
    [K: string]: string;
    foobar: string[];
}

應該注意的是,我想避免使用聯合類型( [K: string]: string | string[]; ),因為在99%的時間內,數據將始終是單個字符串值,因此希望避免鍵入提示。

這可能嗎? 還是我想濫用打字稿?

之所以不起作用,是因為[K: string]: string表示接口中每個鍵的值必須是字符串,並且每個鍵都包含foobar 我建議改做這樣的事情:

interface FormData {
  fields: { [field: string]: string }
  somethingElse: string[]
}

您可以通過使用交集而不是extends 例如:

interface FormData {
    [K: string]: string;
}

type AcmeFormData = FormData & { foobar: string[] };

declare const test: AcmeFormData;

test.foobar       // string[]
test.anythingelse // string

但是,這確實會導致您需要注意一些問題,因為現在索引簽名不再准確。 因此,當打字稿使用該簽名推斷某些內容時,您需要意識到這是錯誤的:

for (let key in test) {
    // val is inferred to have type string, but be careful!
    // In truth, val will be a string[] for the 'foobar' key,
    // but typescript is no longer aware of that. So this will
    // create a runtime error, but compiles without problems!

    const val = test[key].toLowerCase();
}

暫無
暫無

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

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