【问题标题】:What is "Structural Typing for Interfaces" in TypeScript什么是 TypeScript 中的“接口的结构类型”
【发布时间】:2012-09-25 02:16:31
【问题描述】:

在关于 TypeScript 的 blog post 中,Mark Rendle 说,他喜欢它的一件事是:

“接口的结构类型。我真希望 C# 能做到这一点”

他是什么意思?

【问题讨论】:

标签: c# typescript structural-typing


【解决方案1】:

想一想。

class Employee { fire: = ..., otherMethod: = ...}
class Missile { fire: = ..., yetMoreMethod: = ...}
interface ICanFire { fire: = ...}
val e = new Employee
val m = new Missile
ICanFire bigGuy = if(util.Random.nextBoolean) e else m
bigGuy.fire

如果我们说:

interface IButtonEvent { fire: = ...}
interface IMouseButtonEvent { fire: = ...}
...

TypeScript 允许这样做,C# 不允许。

由于 TypeScript 旨在与使用“松散”类型的 DOM 一起工作,因此它是 typescript 的唯一明智选择。

我让读者自己决定他们是否喜欢“结构类型”...... ..

【讨论】:

    【解决方案2】:

    基本上,这意味着接口是基于“鸭子类型”而不是基于类型标识进行比较的。

    考虑以下 C# 代码:

    interface X1 { string Name { get; } }
    interface X2 { string Name { get; } }
    // ... later
    X1 a = null;
    X2 b = a; // Compile error! X1 and X2 are not compatible
    

    以及等效的 TypeScript 代码:

    interface X1 { name: string; }
    interface X2 { name: string; }
    var a: X1 = null;
    var b: X2 = a; // OK: X1 and X2 have the same members, so they are compatible
    

    规范没有详细介绍这一点,但类有“品牌”,这意味着相同的代码,用类而不是接口编写,出错。 C# 接口确实有品牌,因此不能隐式转换。

    考虑它的最简单方法是,如果您尝试从接口 X 到接口 Y 的转换,如果 X 具有 Y 的所有成员,则转换成功,即使 X 和 Y 可能没有相同的名称.

    【讨论】:

      猜你喜欢
      • 2020-03-05
      • 2016-10-06
      • 2021-07-06
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      • 2021-06-16
      • 2018-10-13
      • 2017-06-07
      相关资源
      最近更新 更多