打字稿类型转换对类

时间:2017-12-07 09:38:03

标签: javascript angular typescript

我有一个模型类p

class P {
    constructor(public ids: number[]) {
        console.log(ids);
    }
}

在调用服务api时,我收到了如下响应:

var response: any = { ids: "this is string" }

现在,当我们使用'response'

创建模型P的实例时
let p1 = new P(response.ids);

这会产生错误: ID类型不匹配

但没有错误。

现在问题是如果拒绝响应,如果它与给定的模型类型不匹配?

2 个答案:

答案 0 :(得分:4)

TypeScript汇编为JavaScript。在运行时期间,因此在调用服务API时,类型或类型提示是未知的。这些仅在编译步骤中相关。

如果要检查对象,则应使用typeofinstanceof手动检查api是否使用正确的类型进行响应。如果ids是一个数字数组,您可以这样做:

isArrayOfNumbers(array: any): boolean {
  return Array.isArray(array) && array.every(value => typeof value === 'number');
}

答案 1 :(得分:0)

Typescript被编译为javascript,因此运行时没有类型。如果要显示该消息,则必须明确检查。像Test for array of string type in TypeScript

这样的东西
相关问题