I am working on developing a function that can return different types based on its parameters.
Similar to the function below, but I want it to be more streamlined and efficient (using generics without union types as results)
type ResultType = {
get: GetResult
post: PostResult
...
}
function fetch(operation: keyof ResultType): GetResult | PostResult | ...
To start, I referenced an example from https://www.typescriptlang.org/docs/handbook/2/conditional-types.html. However, when trying to implement the function from the example:
interface IdLabel {
id: number /* + other fields */
}
interface NameLabel {
name: string /* + other fields */
}
type NameOrId<T extends number | string> = T extends number ? IdLabel : NameLabel
function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
if (typeof idOrName === 'number') {
return { id: idOrName }
} else {
return { name: idOrName }
}
}
I encounter errors that are confusing to me:
Type '{ id: number; }' is not assignable to type 'NameOrId<T>'.
Type '{ name: string; }' is not assignable to type 'NameOrId<T>'.
What mistake did I make?
Additionally, is there another way in TypeScript to handle multiple conditional cases effectively (similar to a switch statement)?