问题
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
回答1:
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 possibly async
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 your string values for TA
and TB
type directly. If you use other types like object literals whose string properties you want to have narrowed, you can used as const assertions.
回答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
来源:https://stackoverflow.com/questions/57653776/how-to-match-string-literal-type-when-concat-string-in-typescript