Answer the question
In order to leave comments, you need to log in
How to declare a child type, i.e. a type that necessarily inherits the base type?
The question, I suppose, is trivial, but, having scrolled through the documentation, I did not find the answer. It is necessary to declare a property in the interface or class, which must be inherited from the base one. In some languages, this is solved by declaring the same base type. For example:
interface Foo { }
class A implements Foo { }
class B { }
interface Baz {
someField: Foo; // поле должно наследовать Foo
}
const b: Baz = {
someField: new B(); // ошибка
};
interface Foo { a: number; }
interface Bar extends Foo { b?: number; }
interface Baz extends Foo { c: number; }
class B implements Bar { /* interface release */ }
class C implements Baz { /* interface release */ }
interface X { instance: Bar; }
{ instance: new C() } as X;
Answer the question
In order to leave comments, you need to log in
And where is the mistake?
In general, if I understood the question correctly, you need generics:
class Bar<T extends Foo> {
someField: T; // это поле может быть A, B и обязано произойти от Foo
}
interface Baz<T extends Foo> {
someField: T;
}
I'm looking for a way to unambiguously restrict by ancestor at the type level
declare const hint: unique symbol;
class Foo {
protected [hint]: never;
}
interface IFoo extends Foo {}
class A extends Foo implements IFoo {}
class B { }
interface Baz {
someField: IFoo;
}
const a: Baz = {
someField: new A(), // нет ошибки
};
const b: Baz = {
someField: new B(), // ошибка
};
https://www.typescriptlang.org/play?jsx=0#code/CYU...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question