Class Typescript:有没有办法区分具有相同结构的类?

Class Typescript:有没有办法区分具有相同结构的类?,class,typescript,properties,collision,Class,Typescript,Properties,Collision,当然,这种东西可以用其他方式实现,但我仍然很好奇为什么TS没有发出警告。相同的结构可能有不同的数据 class ComponentContainer<TComponent> extends Array<TComponent> {} class Context<TComponent> extends Array<ComponentContainer<TComponent>> {} ///////////////////////////

当然,这种东西可以用其他方式实现,但我仍然很好奇为什么TS没有发出警告。相同的结构可能有不同的数据

class ComponentContainer<TComponent> extends Array<TComponent> {}

class Context<TComponent> extends Array<ComponentContainer<TComponent>> {}

///////////////////////////////////////////////////////

class Component<T> { constructor(public value: T) {} }

class Movable extends Component<boolean> {
  constructor(value: boolean = true) { super(value) }
}

class Static extends Component<boolean> {
  constructor(value: boolean = true) { super(value) }
}

///////////////////////////////////////////////////////

const ctx: Context<Movable> = new Context()

ctx[0].push(new Static()) // <-- No error
class ComponentContainer扩展数组{}
类上下文扩展数组{}
///////////////////////////////////////////////////////
类组件{构造函数(公共值:T){}
类可移动扩展组件{
构造函数(值:boolean=true){super(值)}
}
类静态扩展组件{
构造函数(值:boolean=true){super(值)}
}
///////////////////////////////////////////////////////
const ctx:Context=new Context()

ctx[0].push(new Static())/在中播放了一段代码后,TypeScript似乎足够聪明,可以检测到
Movable
Static
除了名称之外基本上是相同的类型。它们都是
组件
并且没有属性,因此它允许您将新的
静态
实例推送到
可移动的
数组中。只有当我在
Movable
中添加了一个属性,而该属性在
Static
中不存在时,TypeScript编译器才会显示一个错误,例如:


我想这就是打字脚本的工作原理。它并不一定禁止您在泛型对象上使用不同的类型,除非给定的类型缺少预期类型上存在的属性。这就是为什么下面的方法同样有效:

类型不假定值应该是指定类的实例<代码>可移动
类在此用作接口:

const ctx: Context<Movable> = new Context()
如果不符合以下条件,则会导致TypeScript类型错误:

ctx[0].push({ value: 1 })
通过使用合并接口进行类型检查,还可以将值强制为
Movable
的实例:

ctx[0].push({ value: true })
interface Movable {
    constructor: typeof Movable
}
class Movable extends Component<boolean> {
  constructor(value: boolean = true) { super(value) }
}

谢谢你的解释!我考虑了在运行时使用instanceof作为解决方案的想法。我希望避免这种过程,就像我现在使用“typeof foo===bar”一样,不用客气。通常,您不需要进行
instanceof
验证,除非在其他位置进行
instanceof
检查,因为对象不是类的实例,这将导致运行时错误。上下文保证提供的值与接口匹配,而且大多数情况下已经足够了。在实例化过程中接口匹配之前已经足够了,但是它们各自的构造函数中的逻辑可能不同!祝你一周愉快!但是构造函数逻辑在这里并不重要,因为构造函数是在调用
ctx[0].push之前执行的,它用于生成具有特定接口的对象。在您的情况下,它分配
属性,该属性是公共接口的一部分,可以进行类型检查。这就是为什么接口的概念存在于OOP中。一旦有了与接口匹配的对象,它的来源就无关紧要了。私有字段是确保类型之间不兼容的好方法,两个类即使具有相同的私有字段,从定义上来说也是不兼容的:谢谢!我认为直到现在typescript都是通过匹配正确的语义引用来工作的!是时候拿到那本手册了:)
ctx[0].push({ constructor: Movable, value: 1 });