'Typescript return object with computed property from parameter

I want to do something like

function f<T extends 'a' | 'b'>(t : T): {[t]: ...} {
  return {[t]: ...}
}

such that f('a') has type {'a': ...} and similarly for 'b', but it makes typescript very angry. I've looked at Return type is object where key is computed from argument, How to return object interface with variable as a key in TypeScript? Type is not assignable to type error, and mapped types, but they haven't been especially helpful.

Is this possible in typescript?



Solution 1:[1]

Does this fulfill your needs?

type FReturn<T extends string>={
  [key in T]: string;
};

function f<T extends 'a' | 'b'>(t : T): FReturn<T> {
  return {
    [t]: ''
  } as FReturn<T>
}

let x = f('a')

x.a // string
x.b //error


let y = f('b')

y.b //string
y.a //error

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shahriar Shojib