如何从Typescript对象调用对象函数

时间:2017-11-10 16:12:10

标签: typescript

我试图从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对象中调用对象的函数?

2 个答案:

答案 0 :(得分:0)

Typescript无法确保类型安全,因为您刚才声明日期是随机对象。要解决这个问题,您可以使用Date类型或创建与您需要的方法匹配的接口:

interface hasIsoString {
  toISOString: () => string
}

答案 1 :(得分:0)

此处的问题是 ..., , xaxs="i", yaxs="i", xaxt="n", yaxt="n", ylab="", xlab="") 没有date作为自己的属性。 toISOString方法附加到toISOString()构造函数的原型,而不是任何给定的Date对象。

Date

尽管如此,您不需要进行第三次检查以确保类型安全。通过消除过程,Typescript已经将它视为前两个类型守卫之后的日期:

(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会为您解决。