Hey there, if you're looking for generic values as mentioned in the discussions at Microsoft/TypeScript#17574, you'll find that they aren't readily available in the language except for generic functions. If you feel strongly about this, consider showing your support by liking the issue or sharing your specific use case.
To work around this limitation with a generic interface like:
interface XYZ<T> {
arr: T[],
dict: Partial<T>
}
You can create a generic function to validate a value as being of type XYZ<T>
for any T
, and let type inference determine T
as needed. Avoid directly declaring something as type XYZ
. Here's an example of how you could approach it:
const asXYZ = <T>(xyz: XYZ<T>) => xyz;
const x = asXYZ({
arr: [{ a: 1, b: 2 }, { a: 3, b: 4 }],
dict: { a: 1300 }
}); // results in XYZ<{a: number, b: number}>
This method is often effective in practice as it aligns well with TypeScript conventions. However, it may not fully represent the concept of "I don't care what type T
is."
If you're keen on defining an existential type, although TypeScript doesn't directly support these types, you can simulate it as follows:
interface SomeXYZ {
<R>(processXYZ: <T>(x: XYZ<T>) => R): R
}
const asSomeXYZ = <T>(xyz: XYZ<T>): SomeXYZ =>
<R>(processXYZ: <T>(x: XYZ<T>) => R) => processXYZ(xyz);
The SomeXYZ
type essentially disregards the specifics of T
and holds a reference to XYZ<T>
for an undetermined T
. With asSomeXYZ
, you can create an object of this type:
const someXYZ: SomeXYZ = asSomeXYZ({
arr: [{ a: 1, b: 2 }, { a: 3, b: 4 }],
dict: { a: 1300 }
}); // Returns SomeXYZ
To utilize it, provide a function that processes the referenced value. This function must handle XYZ<T>
for any possible T
:
// Usage example
const xyzArrLength = someXYZ((xyz => xyz.arr.length))
In this scenario, xyzArrLength
will be a number
since the function always returns a number regardless of the actual T
.
While existential types in TypeScript can be cumbersome due to their control flow implications, the workaround I initially shared is often simpler to implement and understand despite its limitations.
Hoping this information proves useful for your needs. Best of luck!
EDIT: Upon revisiting your question, it seems you might actually benefit from the "workaround" solution I suggested earlier. Feel free to give it a try! Cheers.