【问题标题】:TypeScript type casting issue - exampleTypeScript 类型转换问题 - 示例
【发布时间】: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


【解决方案1】:

对 products 数组进行字符串化并再次对其进行解析会使其丢失您之前拥有的任何类型信息。这就是为什么它没有像您期望的那样被读回。

JSON.parse 的返回类型是any

object 类型的对象也无法分配,也无法分配给 IProduct,因为它缺少在该接口上定义的 2 个属性。 object 是一个空对象 {}。

【讨论】:

  • 好吧,当类型为 时,似乎 TypeScript 接口不干涉!非常感谢!
猜你喜欢
  • 2011-11-17
  • 2012-10-01
  • 2010-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多