how to match string literal type when concat strin

2020-02-16 01:52发布

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条回答
Bombasti
2楼-- · 2020-02-16 02:32

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 set your string values to 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.

查看更多
何必那么认真
3楼-- · 2020-02-16 02:34

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

查看更多
登录 后发表回答