【发布时间】:2021-03-21 12:54:27
【问题描述】:
我正在尝试编写一个对象路径实用程序,以确保键列表对应于指定泛型类型中的实际路径。
在我下面的尝试中,我认为通用签名将推断的文字字符串值扩大到简单地为string。如何在我的通用约束中使用文字字符串参数来确保下一个键是前一个键值的键?
class FieldPathBuilder<C,
K1 extends string & keyof C = string & keyof C, // ensure first arg is a valid top-level key
K2 extends string & keyof C[K1] = string & keyof C[K1], // must be a valid key of C[K1]
> {
path(key1: K1, key2?: K2): string {
return '' // not important
}
}
interface A {
first: {
second: {
third: {}
}
},
other: {} // NOTE: the example below compiles if I remove this field
}
new FieldPathBuilder<A>().path('first', 'second') // <-- Error: Argument of type
// '"second"' is not assignable to parameter of type 'undefined'
【问题讨论】:
标签: typescript generics typescript-generics