假設我有一個型別
type Template = {
a: string;
b: string;
c: string
}
我想在函式中使用它,但我想向它添加額外的引數。實施它的最佳方法是什么?
當我嘗試擴展它時,打字稿說? expected
我是這樣做的
const test = (template: Template extends { d: string }[]) => {
template.map(t => console.log(t.d));
}
PS 我不使用 [key:string]: string 這個型別
uj5u.com熱心網友回復:
無法擴展型別。參考這個接受的答案
你可以像這樣解決你的問題
type Template = {
a: string;
b: string;
c: string
}
type NewTemplate = Template & { d: string }
const test = (template: NewTemplate[]) => {
template.map(t => console.log(t.d));
}
uj5u.com熱心網友回復:
如果您不想使用 '&' 來擴展型別,則可以使函式泛型:
const test = <T extends Template>(template: T[]) => {
template.map(t => console.log(t.d))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/436129.html
標籤:打字稿
