I have a type MyType that looks as so
type MyType<V> {
value: V
}
I’m trying to implement a function that takes in a tuple of various MyType objects, and returns the values.
Desired behaviour:
const obj1 = {value:1}
const obj2 = {value: "hello"}
const obj3 = {value: new Date()}
const values = getValues(obj1, obj2, obj3)
// Need typescript to infer that values is of type [number, string, Date]
My attempt (I get an error when I try to return an empty list in the recursive function call):
type Infer<T> = T extends MyType<infer V> ? V : never;
type InferRecursive<T extends any[]> =
T extends [] ?
[] : T extends [infer U, ...infer URem] ?
[Infer<U>, ...InferRecursive<URem>]
: never;
function getValue<T extends MyType<any>>(obj: T): Infer<T> {
return obj.value;
}
function getValues<T extends MyType<any>[]>(...objs: T): InferRecursive<T> {
if (objs.length === 0) {
// *ERROR HERE* --> [] cannot be assigned to InferRecursive<T>
return [];
}
const [next, ...rest] = objs;
return [
getValue(next), ...getValues(...rest)
]
}
Desired behaviour:
const obj1 = {value:1}
const obj2 = {value: "hello"}
const obj3 = {value: new Date()}
const values = getValues(obj1, obj2, obj3)
// Need typescript to infer that values is of type [number, string, Date]
My attempt (I get an error when I try to return an empty list in the recursive function call):
type Infer<T> = T extends MyType<infer V> ? V : never;
type InferRecursive<T extends any[]> =
T extends [] ?
[] : T extends [infer U, ...infer URem] ?
[Infer<U>, ...InferRecursive<URem>]
: never;
function getValue<T extends MyType<any>>(obj: T): Infer<T> {
return obj.value;
}
function getValues<T extends MyType<any>[]>(...objs: T): InferRecursive<T> {
if (objs.length === 0) {
// *ERROR HERE* --> [] cannot be assigned to InferRecursive<T>
return [];
}
const [next, ...rest] = objs;
return [
getValue(next), ...getValues(...rest)
]
}
New contributor
narangkay is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.