简体   繁体   English

TypeScript 中的类和 Generics

[英]Classes and Generics In TypeScript

class Person {
  constructor(public name: string) {}
}

class Manager extends Person {}

class Admin extends Person {}

class School {
  constructor(public name: string) {}
}

function doOperation<T extends Person>(person: T): T {
  return person;
}

let person = doOperation(new Manager("tars"));
let school = doOperation(new School("Harper's"));

why does typescript not throw any error in this case, when School class is clearly not a subclass of Person.为什么 typescript 在这种情况下不会抛出任何错误,而 School class 显然不是 Person 的子类。 Is it because both the classes (Person and School) have a property with same name.是不是因为两个类(Person 和 School)都有同名的属性。

Your example can be simplified to this being OK in typescript您的示例可以简化为在 typescript 中可以

class Person {
    constructor(public name: string) {}
}

class School {
    constructor(public name: string) {}
}

const m: Person = new School("schoolio");

As the tHeSiD says.正如 tHeSiD 所说。 This is how it is in typescript, the above is essentially a demonstration of what 'duck typing' is.这就是 typescript 中的情况,上面基本上是对“鸭子打字”的演示。 A new School("schoolio") has all the properties needed to be a Person, so it can be used as one.一个新的 School("schoolio") 具有成为 Person 所需的所有属性,因此它可以用作一个。

This is great, well I love it, because it means that class relationships don't 'get in the way'.这很棒,我喜欢它,因为这意味着 class 关系不会“妨碍”。 But it is also sometimes annoying, because it means it's easy to call a function with a 'wrong type'但这有时也很烦人,因为这意味着很容易用“错误类型”调用 function

You just need to appreciate that what you lose in safety you gain in functions automatically being very generic;你只需要意识到你在安全上失去的东西,你在功能中获得的东西会自动变得非常通用; no longer are you constrained by having to pass things in of 'exactly the right type' - so long as you pass in objects which have the properties needed to run the function you are good to go.您不再受制于必须传入“完全正确的类型”的东西 - 只要传入具有运行 function 所需属性的对象,您就可以使用 go。

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

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