假设我想做以下事情:
type Car = {
type: 'car'
}
type House = {
type: 'house'
}
add('car', {type: 'car'}) // < this is fine.
add('house', {type: 'car'}) // < this should cause a compile time error.
是否可以编写一个add
强制执行此约束的方法?
另一个要求是,type
您可以添加的内容没有限制。唯一的限制应该是type
s 必须匹配。
稍微修改您的代码以使其按预期工作:
const add = <TObj extends {type: TKey}, TKey extends string>(key: TKey, obj: TObj) => {
/* ... */
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句