Typescript 我怎样才能得到一个“儿童”班;这";对象

Typescript 我怎样才能得到一个“儿童”班;这";对象,typescript,Typescript,所以,我想在typescript中做一些有用的东西 interface Object { safeCall(func: (obj: === typeof this ===) => any | null); } Object.prototype.safeCall = func => { try { const value = func(this); return value ? value : null; } catch {

所以,我想在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)
所以,问题是,我不能处理类型推断,并且我没有类型系统的所有好处,比如自动完成、类型验证、编译检查和其他


如何捕获子类的类型?

您可以将函数设置为泛型,并将泛型类型用作此的类型,然后将类型转发到回调。我还为结果添加了一个泛型类型参数,这可能也很有用

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
接口对象{
safeCall(this:T,func:(obj:T)=>TResult | null):TResult | null;
}
//我们使用正则函数而不是箭头函数,因为
//arrow函数将从声明上下文中捕获此内容
//当我们想要使用函数调用的任何对象时
Object.prototype.safeCall=函数(this:T,func:(obj:T)=>TResult | null):TResult{
试一试{
常量值=func(本);
返回值?值:空;
}抓住{
返回null;
}
};
申报var产品:产品;
const measureUnitID=product.safeCall(obj=>obj.measureUnit.id)//obj将是产品

值得注意:请注意@Titian如何使用原型的完整
函数(){}
表单,而不是箭头函数。这确保了
这个
是正确的。是的,我也应该提到这一点,出于反射而改变它,将添加一个解释,10倍