【问题标题】:How in typescript check if substring match one of in list of strings如何在打字稿中检查子字符串是否与字符串列表中的一个匹配
【发布时间】:2022-12-12 23:24:17
【问题描述】:

让我们考虑例子

type Routes = 'first' | 'second';

type BeforeSign = //...

const handleRoute = (route: BeforeSign<Routes, '#'>) => route;

handleRoute('first');
handleRoute('first#additional');
handleRoute('first#random');
handleRoute('second#example');

// @ts-expect-error
handleRoute('third');
// @ts-expect-error
handleRoute('third#nope');

如何编写BeforeSign泛型类型来使所有handleRoute调用都没有错误?

【问题讨论】:

    标签: typescript generics


    【解决方案1】:

    你可以使用模板文字类型将字符串文字连接在一起。

    type BeforeSign<R extends string, D extends string> = R | `${R}${D}${string}` 
    
    const handleRoute = (route: BeforeSign<Routes, '#'>) => route;
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-30
      • 2013-04-29
      • 2015-07-27
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 2011-06-18
      相关资源
      最近更新 更多