So I am trying to get an object based on the parameter being passed in.
I found this question and it get really close to what I after.
TypeScript function return type based on input parameter
However, I want the function to be able to accept string too, and when the parameters passed in is not in the literal type, it will infer any or unknown
Let me put what I mean in 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>[] {
...
}
Notice that TypeName has union type of literal type and string.
What I hope to see if that, when I use the type, I would be able to infer the return type based on the parameter. For example:
const circle = getItems('circle'); // infers: Circle
const something = getItems('unknown'); // infers: unknown
The above is all good. However, I could not get the IDE to suggest the options.
I expect to see an options of: 'circle' | 'square' | string.
Is that possible to do?
| stringoption inTypeNameit should work in your IDE. Or you can add something liketype TypeName = "circle" | "square" | "unknown";unknowntype.type TypeName = "circle" | "square" | "unknown";. However, I wanttype TypeName = "circle" | "square" | string;, the actualstringtype. The reason behind it is that if the type is not Literal Type that I specified, I would like to use the type value as is.