我需要描述一個介面,其中:
- 具有“billingAddress”鍵的屬性具有具有特定屬性的物件的值,并且
- 具有任何其他鍵的屬性具有字串值。
我試過這個:
interface DoesNotWork {
[key: string]: string;
billingAddress?: {
foo: string;
}
}
打字稿抱怨說Property 'billingAddress' of type '{ foo: string; } | undefined' is not assignable to 'string' index type
很公平:當DoesNotWork.billingAddress被定義時,Typescript 不知道是否應該為它分配 a string、 anobject或undefined。
如何以 Typescript 能夠理解的方式描述界面?
uj5u.com熱心網友回復:
使用有區別的聯合,這樣你就可以混合搭配。
interface DoesNotWork {
billingAddress?: {
foo: string;
};
}
const foo: DoesNotWork | { [key: string]: string } = {
billingAddress: { foo: "value" },
key: "value"
};
uj5u.com熱心網友回復:
使用索引簽名,因為在編譯時不知道確切的 propertyName,但資料的一般結構是已知的,創建一個單獨的 interface來容納這些資料,然后組合 Interfaces來實作所需的物件結構,應該會有所幫助解決您的問題或使用聯合型別進行擴展以增加預期值的靈活性
這是因為在嘗試在同一界面中定義不同欄位時,您必須滿足除索引簽名欄位之外的其他欄位的不同(值)選項
演示代碼
//composition approach(1)
interface BillingAddress{
foo: string;
}
interface DoesNotWork{
[key: string]: string;
}
interface ComposedInterface{
indexSignature: DoesNotWork,
billingAddress? : BillingAddress,
}
//extending value fields using unions approach(2)
interface BillingAddress{
foo: string;
}
interface DoesNotWork{
[key: string]: string | BillingAddress;
billingAddress: BillingAddress;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497070.html
標籤:打字稿
