而不必在其他文件中重複委託的形狀,我該如何聲明對具有給定已知類型打印形狀的函數的引用?你如何聲明一個變量擁有一個通用的委託?
功能:
/**
* @param {object} prev
* @param {object} next
* @param {string} name - the name of the child param of both objects to compare
*/
exports.getModification = <T> (prev:T,next:T, name:string):Modification<T> =>
{
const getIsChanging = p => prev[p] != null && p in next && next[p];
const getIsAdding = p => !prev[p] && p in next && next[p];
const getIsDeleting = p => prev[p] != null && p in next && !next[p];
const result:Modification<T> = (
getIsChanging(name) ? {changeType:'changing',next: next[name]}
: getIsAdding(name)? {changeType:'adding', next: next[name]}
: getIsDeleting(name) ? {changeType:'deleting',next:undefined}
: {changeType:undefined,next:undefined});
return result;
};
我試圖通過
interface Modification<T>{
changeType: string | undefined;
next: T | undefined;
}
interface GetModificationDelegate<T>{
(prev:T,next:T, name:string) : Modification<T>;
}
// try a type alias
type GetModificationFunction<T> = (prev:T,next:T, name:string) => Modification<T>;
這些都寫的方法/委託的定義編譯就好了。然而,告訴打字稿符號是對此失敗的一個參考。
var getModification = (app.getModification as GetModificationFunction<T>);
var getModification: <T>GetModificationFunction<T> = app.getModification;
var getModification: <T extends{}>GetModificationFunction<T> = app.getModification;
這些都不編譯。而不訴諸類(我認爲這很簡單)我怎樣才能簡單地告訴打字稿一些東西是它已經知道的一個形狀的一般代表?
我可以在一個類中包裝消費者聲明嗎?將屬性/靜態方法定義爲'GetModificationFunctionType'? –
Maslow
是的,你可以在課堂上有聲明,但它不能是靜態的。我更新了答案。 – artem