G
G
Gennady S2021-09-22 09:40:59
typescript
Gennady S, 2021-09-22 09:40:59

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(); // ошибка
};

UPD more descriptive example:
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

1 answer(s)
D
Dmitry Belyaev, 2021-09-22
@gscraft

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;
}

UPD:
I'm looking for a way to unambiguously restrict by ancestor at the type level

You can check this hint:
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 question

Ask a Question

731 491 924 answers to any question