所以,我想在typescript
中做一些有用的事情interface Object {
safeCall(func: (obj: === typeof this ===) => any | null);
}
Object.prototype.safeCall = func => {
try {
const value = func(this);
return value ? value : null;
} catch {
return null;
}
};
interface MeasureUnit {
id: number;
title: string;
}
interface Product {
id: number;
title: string;
measureUnit: MeasureUnit | null;
}
const product = fetch('....some request');
// obj.measureUnit can be null
const measureUnitID = product.safeCall(obj => obj.measureUnit.id)
所以,问题是,我无法处理类型推断,并且我没有获得类型系统的所有利润,例如自动完成,类型验证,编译检查和其他
我怎样才能捕捉到儿童类的类型?
答案 0 :(得分:2)
您可以使函数通用,并使用泛型类型作为this
的类型,并将类型转发给回调。我还为结果添加了泛型类型参数,这可能也很有用。
interface Object {
safeCall<T, TResult>(this: T, func: (obj: T) => TResult | null) : TResult | null;
}
// We use a regular function not an arrow function because
// the arrow function would capture this from declaration context
// while we want to use as this whatever object the function gets called on
Object.prototype.safeCall = function<T, TResult>(this: T, func: (obj: T) => TResult | null) : TResult{
try {
const value = func(this);
return value ? value : null;
} catch {
return null;
}
};
declare var product: Product;
const measureUnitID = product.safeCall(obj => obj.measureUnit.id) //obj will be Product