简体   繁体   English

在打字稿中连接字符串时如何匹配字符串文字类型

[英]how to match string literal type when concat string in typescript

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.但是get${a}Detail返回一个字符串类型。 And it doesn't match type TB.它与类型 TB 不匹配。

Is there any solutions to solve the problem here?这里有解决问题的方法吗?

Thanks谢谢

This is possible with TypeScript 4.1 Template Literal Types + const assertions / as const :这可以通过 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 操场

TypeScript will not infer a concatenated string to a custom type automatically so you'll have to infer it to TB manually: TypeScript 不会自动将连接字符串推断为自定义类型,因此您必须手动将其推断为TB

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

See code snippet at CodeSandbox在 CodeSandbox 查看代码片段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM