2023-02-17

Typescript generic function that returns key of union parameter

I would like to write a function that returns an object, whose key is based on the parameter. I would like this to be statically typed, and I think it should be possible as the value is present at transpile time. Here is the example:

type ResponseKeys = 'a' | 'b';

interface A {
    city: string;
}

interface B {
    town: string;
}

interface Result<T> {
    data: T | null;
}

function transform<T>(operationName: ResponseKeys): { [operationName in ResponseKeys]?: Result<T> } {
    return {
        [operationName]: {
            data: null,
        },
    };
}

console.log(transform<A>('a'));

Try it out on Typescript playground

I get the function response I want, but the type signature for transform() is:

{
    a?: Response<A> | undefined;
    b?: Response<A> | undefined;
}

I am hoping to narrow and better define it to:

{
    a: Response<A>;
}

i.e. with only the specified key, and without it being a union with undefined.



No comments:

Post a Comment