简体   繁体   English

TypeScript泛型的类型安全

[英]Type safety of TypeScript Generic

I am not sure if I am doing it wrong, or if this is by design... 我不确定是否做错了,还是设计使然...

In my class 在我班上

class List<T> { ... }

I have a method 我有办法

public Add(value: T): void { ... }

I create an instance of my list 我创建列表的一个实例

const fooList: List<foo> = new List<foo>();

but now I can still do 但现在我仍然可以

fooList.Add(new bar());

with foo and bar being unrelated types. foo和bar是不相关的类型。 This triggers no compiler warning, and I am a bit put off by that. 这不会触发任何编译器警告,对此我有点推迟。

Am I doing it wrong, or is that as expected? 我做错了吗,还是按预期进行?

Am I doing it wrong, or is that as expected? 我做错了吗,还是按预期进行?

If types are compatible then it will be allowed eg 如果类型兼容,则将被允许,例如

class List<T> {
  add(val: T) { }
}

class Animal { name: string; }
class Cat extends Animal { meow() { } }

const animals = new List<Animal>();
animals.add(new Animal()); // Okay 
animals.add(new Cat()); // Okay 

const cats = new List<Cat>();
cats.add(new Animal()); // Error 

More 更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM