TypeScript中如何使用type语句实现模板字面量类型移除指定后缀字符串
你可以通过 TypeScript 条件类型搭配 infer 关键字做字符串模式匹配,实现和运行时函数完全一致的类型运算效果,修改后的代码如下:
declare function foo<T extends string>(str: `${T}Bar`): T; const justFoo = foo('fooBar'); // justFoo 的类型会被推导为字面量类型 'foo' // 工具类型实现 type Foo<T extends string> = T extends `${infer Prefix}Bar` ? Prefix : never; type JustFoo = Foo<'fooBar'>; // JustFoo 的类型同样为字面量类型 'foo'
逻辑说明
- 用
extends判断传入的字符串字面量是否符合「前缀 + 固定后缀Bar」的格式 - 用
infer关键字自动推断匹配到的前缀部分,存到自定义的Prefix类型变量中 - 匹配成功直接返回前缀,匹配失败默认返回
never作为兜底,你也可以根据业务需求调整兜底逻辑(比如返回原类型T)
边界测试示例
type Test1 = Foo<'helloBar'> // 类型为 'hello' type Test2 = Foo<'barNoSuffix'> // 不符合格式,类型为 never
内容的提问来源于stack exchange,提问作者casr
相关产品推荐
相关产品推荐

