【问题标题】:TypeScript: "extends" string literal type check not workingTypeScript:“扩展”字符串文字类型检查不起作用
【发布时间】:2021-12-21 15:05:18
【问题描述】:

在尝试键入检查对象中键和值之间的依赖关系时,我尝试将MyObject 定义为:

type Key =  AKey| BKey
type AKey = `A${string}`
type BKey = `B${string}`
type Item<Key> = 
   Key extends AKey ? {a:string} : 
   Key extends BKey ? {b:number} : 
   {}
type MyObject = {[key:Key]:Item<Key>}

没有错误,但是无效的输入被接受而没有错误:

let test1:MyObject = {"Afoo":{a:"yes"}}
let test2:MyObject = {"Afoo":{b:1}} // should fail
let test3:MyObject = {"Bbar":{a:"no"}} // should fail
let test4:MyObject = {"Bbar":{b:2}}

看起来extends 不适用于字符串字面量类型,还是其他类型?

我知道 as const 用于一组封闭的键,但这不适用于这里,因为我需要将键设置为无限。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    正如现在写的 MyObject 结果:

    {
        [key: `A${string}`]: { a: string } |  { b: number };
        [key: `B${string}`]: { a: string } |  { b: number };
    }
    

    这是因为联合 AKey| BKey 被传递给 Item&lt;Key&gt;。但是我们想分别解析每个键的值。这可以使用mapped type 来实现:

    type MyObject = { [K in Key]: Item<K> }
    
    let test1: MyObject = { "Afoo": { a: "yes" } }
    let test2: MyObject = { "Afoo": { b: 1 } } // now fails
    let test3: MyObject = { "Bbar": { a: "no" } } // now fails
    let test4: MyObject = { "Bbar": { b: 2 } }
    

    现在MyObject 被解析为:

    {
        [key: `A${string}`]: { a: string };
        [key: `B${string}`]: { b: string };
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 2013-07-24
      • 2016-04-30
      • 1970-01-01
      • 2017-03-31
      相关资源
      最近更新 更多