Let's say we have an enum, "Profession":
enum Profession {
Teacher = "Teacher",
Scientist = "Scientist",
Rapper = "Rapper",
}
And we have a Person interface, which accepts a generic drawn from Profession's values:
interface Person<P extends Profession> {
profession: P;
}
And finally, we want to implement Person:
class AmericanCitizen implements Person<Profession.Teacher> {
// ... problem continued below
}
... within the class implementation, I'd like to assign the generic-specified profession like so:
class AmericanCitizen implements Person<Profession.Teacher> {
profession = Profession.Teacher;
}
This results in the following TS error:
Property 'profession' in type 'AmericanCitizen' is not assignable to the same property in base type 'Person<Profession.Teacher>'.
Type 'Profession' is not assignable to type 'Profession.Teacher'.
The compiler forces me to do the long-hand equivalent:
class AmericanCitizen implements Person<Profession.Teacher> {
profession: Profession.Teacher;
constructor() {
this.profession = Profession.Teacher;
}
}
Why is it that the former is invalid?
profession = Profession.Teacher as Profession.Teacherworks for some reason as well (playground).