【问题标题】:is it possible to check if the sentence include a certain word using keyword type in typescript?是否可以使用打字稿中的关键字类型检查句子是否包含某个单词?
【发布时间】:2022-01-20 02:46:54
【问题描述】:

我对 typescript 中的 type 关键字有疑问。
你可以看到下面的代码。
参数必须在前缀中包含单词 ('api')。
当然,我可以使用indexOf等编码进行检查。
但我只想使用 type 关键字。

interface SomethingParam {
  url: string
}
function check(url: SomethingParam) {
  console.log(url);
}

check({ url: 'foobar' }) // error
check({ url: 'api/foobar' }) // ok

【问题讨论】:

    标签: typescript typescript-types


    【解决方案1】:

    你可以试试看

    function check(url: `api/${string}`) {
      console.log(url);
    }
    
    check('foobar') // error
    check('api/foobar') // ok
    

    【讨论】:

    • 非常感谢!!比我想象的要容易ㅠㅠ
    猜你喜欢
    • 2020-07-06
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    相关资源
    最近更新 更多