Abhijith
Abhijith

Reputation: 2642

Resolving Typescript types at runtime

How can I get a map for type A at runtime ? The following code fails to compile with this error.

Argument of type 'A' is not assignable to parameter of type '"A" | "B" | "C"'. Type 'A' is not assignable to type '"C"'

type A = {
  a: string;
};

type B = {
  b: string;
};

type C = {
  c: string;
};

const maps = {
  A: (A) => {},
  B: (B) => {},
  C: (C) => {},
};

function getMap(source: keyof typeof maps) {
    return maps[source];
}

const source: A = {
    a: 'test'
}
getMap(source);

Upvotes: 1

Views: 562

Answers (1)

bobkorinek
bobkorinek

Reputation: 695

In TypeScript, you can't get the type of the variable at runtime. The only thing you can do is to create a constant identifier for each of the types you have defined and based on this identifier you can choose your desired function.

type A = {
  id: 'A';
  a: string;
};

type B = {
  id: 'B';
  b: string;
};

type C = {
  id: 'C';
  c: string;
};

const maps = {
  A: (A) => {},
  B: (B) => {},
  C: (C) => {},
};

function getMap(source: A | B | C) {
    return maps[source.id];
}

const source: A = {
    id: 'A',
    a: 'test'
}
getMap(source);

Upvotes: 2

Related Questions