1
type TA = 'App' | 'Area';
type TB = 'getAppDetail' | 'getAreaDetail';
const a: TA = 'App';
const b: TB = `get${a}Detail`;

But get${a}Detail returns a string type. And it doesn't match type TB.

Is there any solutions to solve the problem here?

Thanks

2 Answers 2

2

This is possible with TypeScript 4.1 Template Literal Types + const assertions / as const:

// given
type TA = 'App' | 'Area';
type TB = 'getAppDetail' | 'getAreaDetail';
const a: TA = 'App';
const aError = 'Nap';

// tests
const bInferred = `get${a}Detail` as const; // "getAppDetail"
const bChecked: TB = `get${a}Detail` as const; // works
const bChecked_Error: TB = `getNapDetail`; // error
const bChecked_Error2: TB = `get${aError}Detail` as const; // error

Playground

Sign up to request clarification or add additional context in comments.

Comments

2

TypeScript will not infer a concatenated string to a custom type automatically so you'll have to infer it to TB manually:

type TA = 'App' | 'Area';
type TB = 'getAppDetail' | 'getAreaDetail';
const a: TA = 'App';
const b = `get${a}Detail` as TB;

See code snippet at CodeSandbox

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.