【发布时间】: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