Home > Net >  Is there a way to dynamically type section of a TypeScript interface?
Is there a way to dynamically type section of a TypeScript interface?

Time:10-05

I want to have a TypeScript object be extended by a type. For example:

interface BaseInterface<T> {
  staticA: string;
  staticB: number;
  dynamicA: T;
}

BaseInterface<SomeOtherInterfaceOrType>

When used like so, it should define dynamicA type as SomeOtherInterfaceOrType.

How can this behaviour be achieved? How can I create another interface that is of that type?

CodePudding user response:

Type aliases are your friend: You can create type aliases using syntax similar to variable declaration. This way, you can permanently fix your generic interface to a concrete type, and this can be done an infinite amount of times, for any type matching T (in this case, because T isn't constrained - any type). Generic types are just type/interface factories.

interface BaseInterface<T> {
  staticA: string;
  staticB: number;
  dynamicA: T;
}

type ConstrainedToSymbol = BaseInterface<Symbol>;
// mostly equivalent interface fixing:
interface ConstrainedToNumber extends BaseInterface<number> {}

type ConstrainedToString = BaseInterface<string>;

function func(cbs: ConstrainedToString):string {
 return cbs.dynamicA // Always a string!
}

Check out this playground.

  • Related