Search code examples
typescripttypescript-genericstype-inference

is there a way in ts to just restrict key of the object during generic infer?


is there a pattern or utility type to allow type guard for keys during infer a object in a generic field ?

i would like to know if i can use it like this or if is there knowing approche to do similar ?

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 

thanks for any tips or documentation you can bring to me.


Solution

  • No you cant.

    The {a:8,b:4,c:8} is compatible to the {a:8,b:4} so it fulfilled what the function foo1/foo2 need.

    Even you provide an extra field c in the parameter but the function foo1/foo2 would never know or use such field.

    It is the same situtation if you provide an instance of a sub class to a function which require an instace of super class.