我正在開發一個自定義介面,我希望能夠在其實作中推斷介面值的型別,而不是在介面定義中,沒有泛型。我應該補充一點,這些實作將始終是物件文字而不是類。
這是我正在嘗試做的事情:
interface Defintion {
params: unknown; // Should resolve to the type in the implementation
handler: (dummy: this["params"]) => void; // I want `this` to refer to the implementation, not the interface
}
const customDefn: Defintion = {
params: { test: "Hello World" },
handler: (dummy) => {
// TS Complains here
console.log(dummy.test)
}
}
我想要發生的是customDefn.params
要解決的型別{ test: "Hello World" }
(所以我可以在 中自動完成handler
)而不是保留為unknown
.
我知道我可以使用泛型:
interface Defintion<T> {
params: T;
handler: (dummy: this["params"]) => void;
}
但是,我將不得不定義params
兩次(因為我也以params
編程方式使用):
const customDefn: Defintion<{ test: "Hello World" }> = {
params: { test: "Hello World" },
handler: (dummy) => {
console.log(dummy.test)
}
}
這會變得很麻煩。
uj5u.com熱心網友回復:
關鍵字this
不能用于參考介面中的其他屬性。事實上,使用獨立型別,不可能在屬性之間進行任何交叉參考。
相反,您可以使用通用輔助函式來實作此目的。
interface Defintion<T> {
params: T;
handler: (dummy: T) => void;
}
function createDefiniton<T>(definiton: Defintion<T>) {
return definiton
}
createDefiniton({
params: { test: "Hello World" },
handler: (dummy) => {
console.log(dummy.test)
}
})
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/486822.html
標籤:javascript 打字稿 界面
下一篇:物件回傳陣列的關鍵字搜索