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
What you want is probably something like a string literal expression type or Regex-validated string type. Currently both are not possible unfortunately.
The type system requires to be statically analyzable - in your example, you have a simple string expression
get${a}Detail
, but what if you for example invoke a possiblyasync
function to generate your${a}
string or do other dynamic concatenations? That will be hard to analyze or even not be possible. According to the first issue, regex types have a higher chance of getting implemented (and have decent discussion activity on GitHub).Workaround now is to just set your string values to
TA
andTB
type directly. If you use other types like object literals whose string properties you want to have narrowed, you can usedas const
assertions.TypeScript will not infer a concatenated string to a custom type automatically so you'll have to infer it to
TB
manually:See code snippet at CodeSandbox