#Is it possible to map enum to function return type

4 messages · Page 1 of 1 (latest)

nova zenith
#
I have a setup like the following:

enum Input {
    A,
    B,
    C
}


function returnValue(input: Input) {
    switch (input) {
        case Input.A:
            return 1;
        case Input.B:
            return 'B';
        case Input.C:
            return false;
    }
}

let x = returnValue(Input.A);

I would like to map the different enum values of Input to different return types, so that when I call it with a given input I am given a specific type output. (in this case "X" would be number not string | number | boolean)

I know I can add function overloads like this

function returnValue(input: Input.A): number;
function returnValue(input: Input.B): string;
function returnValue(input: Input.C): boolean;
function returnValue(input: Input): number | string | boolean {

But I was hoping there was a "cleaner" solution, in my project there would be quite a lot of overloads here, so simply being able to map out Input.A: number somewhere would be far nicer if

last muskBOT
#
Burrito#6903

Preview:```ts
enum Input {
A,
B,
C,
}

type ReturnMap = {
[Input.A]: number
[Input.B]: string
[Input.C]: boolean
}

function returnValue<T extends Input>(
input: T
): ReturnMap[T]
function returnValue(input: Input) {
swi
...```

spiral jackal
#

Not sure how much better it is tbh.

nova zenith
#

Awsome thanks thats what I was looking for. Means I can just define it in a file and reference it elsewhere, especially as I have multiple methods that use this pattern so I don't have to make changes all over when I add a new one.