I have a list of different types:
type A = 1
type B = 2
type X = 'x'
type Y = 'y'
An object will be received in the format Record<string, A | B>
. For example: { test1: A, test2: B, test3: A}
. The goal is to create a function that returns this type: { test1: X, test2: Y, test3: X }
There is an attempt at achieving this using TypeScript with mapping A
to X
and B
to Y
, but the desired outcome has not been achieved:
function transform <U extends string> (p: Record<U, A | B>): Record<U, Result<A | B>> {
const result = {} as Record<U, Result<A | B>>
(Object.keys(p) as U[]).forEach(k => (result[k] = p[k] === 1 ? 'x' as const : 'y' as const))
return result
}
const a = transform({ test1: 1 as const, test2: 2 })
// a: Record<"test2" | "test1", "x" | "y">
// So a.test1 is of type 'x' | 'y' and not 'x'
It is uncertain if this approach is feasible in TypeScript when the exact input shape is unknown...
Examples:
input type | result type |
---|---|
{ foo: A; bar: B } | { foo: X; bar: Y } |
{ test1: A; test2: B; test3: A } | { test1: X; test2: Y; test3: X } |
{ test1: A; test2: A; test3: A } | { test1: X; test2: X; test3: X } |
{ stuff: A } | { stuff: X } |
The objective is for the transform
function to ensure that:
- If a key is not present in the input, it should not appear in the output.
- If
input[key]
was of type A, thenoutput[key]
should be inferred as typeX
.
Is this achievable?