У меня есть typescript@3.4.0-dev.20190228.
Работа над машинописью в следующем коде непостижима:
class Container<T = any> {
constructor(private parent: Parent<T>) {}
}
class Parent<T = any> {
constructor(private children: Child<T>[]) {}
}
class Child<T = any> {
constructor(private model: T) {}
}
class Model1 {
prop1: string = '';
prop2: number = 123;
}
class Model2 {
otherProp1: boolean = true;
otherProp2: object = {};
}
const parentInstance = new Parent<Model1>([
new Child(new Model2()), // Error --> It's OK
new Child(new Model1()),
new Child(new Model1()),
]);
const containerInstance = new Container<Model2>(
new Parent([
new Child(new Model2()), // Error --> Why!?
new Child(new Model1()),
new Child(new Model1()),
])
);
См. Также этот код на Игровая площадка TypeScript .
- Почему универсальный для
Container
игнорировать тип Model2
(см. containerInstance
настройка)? - Почему, когда я изменяю универсальный для
Parent
на Model2
, это влияет на Container
(см. настройку parentInstance
)? - Почему, когда я изменяю порядок настройки
containerInstance
, это имеет значение?
const containerInstance = new Container<Model2>(
new Parent([
new Child(new Model2()),
new Child(new Model1()), // Error --> It's OK
new Child(new Model1()), // Error --> It's OK
])
);
const parentInstance = new Parent<Model1>([
new Child(new Model2()), // Error --> It's OK
new Child(new Model1()),
new Child(new Model1()),
]);
Обновление: Я открыл вопрос на github