简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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