0
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. Is it because both the classes (Person and School) have a property with same name.

2
  • 1
    because they have the exact same properties, try changing name in school to schoolName ie public schoolName: string and it will throw an error. Commented May 29, 2021 at 18:45
  • 1
    Typescript uses a structural typing system, and not a nominal typing system. This means types that have the same interface, are considered the same type. Commented May 29, 2021 at 19:20

1 Answer 1

2

Your example can be simplified to this being OK in typescript

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

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

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

As the tHeSiD says. This is how it is in typescript, the above is essentially a demonstration of what 'duck typing' is. A new School("schoolio") has all the properties needed to be a Person, so it can be used as one.

This is great, well I love it, because it means that class relationships don't 'get in the way'. But it is also sometimes annoying, because it means it's easy to call a function with a 'wrong type'

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.