我想在打字稿中拆分型別規范和函式的實作
例如:
如果我有這樣的型別
type MyFuncType = () => void
我可以創建一個作為該型別實體的實作,如下所示:
const myFuncImp: MyFuncType = () => {
//implementation
}
我現在想用型別引數來做到這一點。我的方法不起作用:
type MyFuncType<T> = () => void
const myFuncImp: MyFuncType = () => {
//implementation
}
這會導致錯誤:
Generic type 'MyFuncType' requires 1 type argument(s)
還有另一種方法可以做到這一點嗎?
uj5u.com熱心網友回復:
將泛型引數附加到函式型別而不是型別別名:
type MyFuncType = <T>(a: string) => void;
// instead of: type MyFuncType<T> = () => void;
const myFuncImp: MyFuncType = <T>(a) => {
//implementation
const myArray: T[] = [];
a.endsWith("foo")
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496462.html
