【发布时间】:2017-08-24 03:49:38
【问题描述】:
我在 TypeScript 中遇到了“类型转换接口”问题。我不明白为什么我的界面没有干扰!请参阅下面的示例:
interface IProduct {
age : number;
price : number;
}
class Product{
public age: number = 22;
}
let products : Array<Product> = [new Product(), new Product()];
let products_stringify = JSON.stringify(products);
let products_parsed = JSON.parse(products_stringify);
**// Now my problem starts here....**
// Why interface IProduct does not interfere ?
let firstProduct1: IProduct = products_parsed[0];
console.dir(typeof products_parsed[0]);// -> object
// When i do a typecasting with <object> the interface interferes, and throws an error!
let firstProduct2 : IProduct = <object>products_parsed[0];
console.dir(typeof products_parsed[0]);// -> object
【问题讨论】:
-
您正在筛选产品并再次阅读它们。这会使它们丢失任何类型信息。
-
Product 也没有正确实现 IProduct 接口,它缺少 price 属性。
-
价格属性的缺失是有意的。如果我检查第一个产品对象的类型(解析后),它在这两种情况下都是“对象”类型......在第一个例子中,接口 IProduct 必须干预......但它没有!
标签: typescript interface casting