【问题标题】:How to call object function from Typescript object如何从 Typescript 对象调用对象函数
【发布时间】:2017-11-11 06:45:59
【问题描述】:

我正在尝试从 TypeScript 调用 Date 对象上的函数,但它不允许我这样做。我在 if/else 中执行此操作,并且我已经消除了其他两种允许的原始类型。我只是不知道如何使用 TypeScript 中的对象类型。 TypeScript 对象上可用的函数似乎都不合适。 代码如下:

const formatDate = (date: string | number | object): string | null => {
    if (typeof date === 'string') return date ? new Date(date).toISOString() : null;
    else if (typeof date == 'number') return date != null ? new Date(date).toISOString() : null;
    else if (date.hasOwnProperty('toISOString')) return date.toISOString();
    else return null;
}

我得到错误:

TS2339: Property 'toISOString' does not exist on type 'object'.   

有没有办法从 Typescript 对象调用对象的函数?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    Typescript 不能保证类型安全,因为您刚刚说过 date 是一个随机对象。要解决这个问题,您可以使用 Date 类型或创建与您需要的方法相匹配的接口:

    interface hasIsoString {
      toISOString: () => string
    }
    

    【讨论】:

    • 哦,是的,我确实在蛋头视频中看到了这一点。我只是忘记了。顺便说一句,我确实使用了 Date 类型,但我得到了同样的错误。
    • 我再次尝试了 Date,它现在可以工作了。我可能还有其他问题。
    【解决方案2】:

    这里的问题是date 没有toISOString 作为它自己的属性。 toISOString() 方法附加到 Date 构造函数的原型,而不是任何给定的 Date 对象。

    (new Date()).hasOwnProperty('toISOString')   //false
    Date.prototype.hasOwnProperty('toISOString') //true
    

    不过,您不需要第三次检查来确保类型安全。 Typescript 已经通过消除过程将其视为前两个类型保护之后的日期:

    const formatDate = (date: string | number | Date) => {
        if (typeof date === 'string') return date ? new Date(date).toISOString() : null;
        else if (typeof date == 'number') return date != null ? new Date(date).toISOString() : null;
        return date.toISOString();
    }
    
    formatDate('2017-11-10');              //"2017-11-10T00:00:00.000Z"
    formatDate(1510300800000);             //"2017-11-10T00:00:00.000Z"
    formatDate(new Date(2017, 10, 10));    //"2017-11-10T00:00:00.000Z"
    formatDate({ foo: 'bar' });            //not allowed
    

    但是,如果您要以某种方式使编译后的代码在非 Typescript 环境中可用,理论上您可以像这样更改您的第三次检查,只是为了安全起见:

    const formatDate = (date: string | number | Date) => {
        if (typeof date === 'string') return date ? new Date(date).toISOString() : null;
        else if (typeof date == 'number') return date != null ? new Date(date).toISOString() : null;
        else if (date instanceof Date) return date.toISOString();
        return null;
    }
    
    formatDate('2017-11-10');              //"2017-11-10T00:00:00.000Z"
    formatDate(1510300800000);             //"2017-11-10T00:00:00.000Z"
    formatDate(new Date(2017, 10, 10));    //"2017-11-10T00:00:00.000Z"
    formatDate({ foo: 'bar' });            //still not allowed, but would return null if it were
    

    另请注意,在任何一种情况下,您都不需要在此函数上显式指定返回类型 - Typescript 会为您解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 2010-10-01
      • 1970-01-01
      相关资源
      最近更新 更多