In TypeScript, I am trying to write a function that takes a string as one of its inputs,…
- User
In TypeScript, I am trying to write a function that takes a string as one of its inputs, and produces and object with that string in one of it's keys. I'm sending a narrowly types string but in the output object it always gets expanded to the general
stringtype, even if I useas conston the object. Below is a minimal example to reproduce the problem. How can I get the object key to typed asmyABCinstead ofstring?const s = 'ABC' as const; const fn = <S extends string>({ name }: { name: S }) => ({ name, [`my${name}`]: 5 } as const); const x = fn({ name: s } as const); type X = typeof x; // X is type { readonly [x: string]: 'ABC' | 5, readonly name: 'ABC' } type ABC = X['myABC']; // expected type ABC to be 5, not 'ABC' | 5 Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.