1

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);
1
  • getMap takes a type of 'A' | 'B' | 'C' as an argument, not A | B | C, so to make it work you need to call it as getMap('A') , but it's probably not what you wanted, because it requires the type name, not the type itself. Commented Dec 30, 2021 at 19:39

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.