Dynamic generic type inference for object literals

2020-06-18 04:07发布

问题:

In typescript, I can declare a generic function like so:

const fn: <T>(arg: T)=>Partial<T>

In this case, TypeScript can sometimes infer the type parameter of the function based on the actual parameters I pass it. Is there a similar way to define a generic object literal whose type parameter can be dynamically inferred based on its contents? Something like:

interface XYZ { 
  obj: <T>{ arr: T[], dict: Partial<T> }
}

I am aware I can make the entire interface generic like so:

interface XYZ<T> {
  arr: T[],
  dict: Partial<T>
}

but I want to avoid that, because then I would have to declare the generic type in advance whenever I am using the interface. For example

const x: XYZ

will not work. If I want to make the declaration general, I am forced to write:

const x: XYZ<any>

but this does not allow TypeScript to dynamically infer the specific generic type based on the actual contents of x

回答1:

Ah, you want generic values as discussed in Microsoft/TypeScript#17574. As you note, they don't exist in the language except in the case of generic functions. You can go give a