Currently, my goal is to retrieve an object based on the parameter being passed in.
I came across a similar question that almost meets my requirements.
TypeScript function return type based on input parameter
However, I want to enhance the function's capability to accept strings as well. In cases where the parameters passed in are not of the literal type, it should infer any or unknown
Let me illustrate what I mean with some code.
interface Circle {
type: "circle";
radius: number;
}
interface Square {
type: "square";
length: number;
}
type TypeName = "circle" | "square" | string;
type ObjectType<T> =
T extends "circle" ? Circle :
T extends "square" ? Square :
unknown;
function getItems<T extends TypeName>(type: T) : ObjectType<T>[] {
...
}
Note that TypeName
has a union type of both literal types and string.
My expectation is to be able to infer the return type based on the parameter when using the type. For example:
const circle = getItems('circle'); // infers: Circle
const something = getItems('unknown'); // infers: unknown
The above functionality works perfectly fine. However, I am unable to get the IDE to suggest the options.
I anticipate seeing options like: 'circle' | 'square' | string
.
Is it feasible to achieve this?