是否有一种模式或实用程序类型允许在推断通用字段中的对象时对键进行类型保护?
我想知道我是否可以这样使用它,或者是否有知道方法可以做类似的事情?
type Data = {
a:number
b:number
}
function foo1<T extends Data >(o:T) {}
function foo2<const T extends Data >(o:T) {}
foo1({a:8,b:4,c:8}) // i want error "only know key in Data are allowed" : c is not in Data
foo2({a:8,b:4,c:8}) // i want error "only know key in Data are allowed" : c is not in Data
感谢您给我提供的任何提示或文档。
不,你不能。
{a:8,b:4,c:8}
与{a:8,b:4}
兼容,因此它满足了foo1/foo2
功能的需要。
即使你在参数中提供了额外的字段
c
,但函数foo1/foo2
永远不会知道或使用这样的字段。
如果您向需要超类实例的函数提供子类的实例,情况也是一样。