I’m trying to write a TypeScript function that takes an object, performs a function on each key of that object and returns it. However I can’t get the types to play nice so that the return object is typed the same as the input object when union types are used.
Let’s say we have a few types:
type FirstType = {
type: 'first';
};
type SecondType = {
type: 'second';
data: {
label: string;
};
};
type ThirdType = {
type: 'third';
data: {
url: string;
};
};
type SomeUnion = FirstType | SecondType | ThirdType;
And I want to write a function that will take an array of these objects with the union type and e.g. replace ‘http://’ with ‘https://’ on all keys in the object on the data
key of the union type, returning the full object:
const objectKeys = <T extends Record<string, any>>(obj: T): Array<keyof T> =>
Object.keys(obj);
const replacer = (data: string): string => data.replace('http://', 'https://');
function transformValue(value: SomeUnion): SomeUnion {
return 'data' in value // Error: Property 'label' is missing in type '{ url: string; }' but required in type '{ label: string; }'
? {
...value,
data: objectKeys(value.data).reduce((data, key) => {
return {
...data,
[key]: replacer(data[key]),
};
}, value.data),
}
: value
}
const processor = (data: SomeUnion[]): SomeUnion[] =>
data.reduce(
(acc, value) => ({
count: acc.count + 1,
newData: [...acc.newData, transformValue(value)],
}),
{
count: 0,
newData: [] as SomeUnion[],
}
).newData;
(Whilst I’m not using it in my example, the extra count
data on the reducer is important for my actual implementation so it’s important to maintain that in the solution.)
The problem I have is that while this works, TypeScript complains that the type of the data
becomes a union type in itself which isn’t compatible with UnionType
, i.e.
{
type: 'second';
data: {
label: string;
} | {
url: string;
};
} | {
type: 'third';
data: {
label: string;
} | {
url: string;
};
};
Note that the union type comes from a library so I’d rather not change the types if I can avoid it.
Playground
5
TypeScript does not directly support correlated unions as discussed in microsoft/TypeScript#30581. It does not check a single line of code multiple times, speculatively narrowing union-typed values to each of union members. If you have code like ⋯x⋯
that fails to type check when x
is a union type, but does work when x
is any of the members of the union type, then you’ve run into a problem with correlated unions. Your transformValue()
function body is one such piece of code.
By far the easiest thing to do is use a type assertion and move on with your life:
function transformValue(value: SomeUnion): SomeUnion {
return ('data' in value ? {
...value, data: objectKeys(value.data).reduce((data, key) => {
return {
...data,
[key]: replacer(data[key]),
};
}, value.data),
} : value) as SomeUnion // assert
}
Or, if you don’t mind redundancy, you could do the narrowing yourself that TypeScript doesn’t do:
function transformValue2(value: SomeUnion): SomeUnion {
return 'data' in value ? value.type === "second" ?
{
...value, data: objectKeys(value.data).reduce((data, key) => {
return { ...data, [key]: replacer(data[key]), };
}, value.data), // redundant
} : {
...value, data: objectKeys(value.data).reduce((data, key) => {
return { ...data, [key]: replacer(data[key]), };
}, value.data), // redundant
} : value
}
Otherwise, the only approach that comes close to TypeScript verifying the correctness for you is described at microsoft/TypeScript#47109 and involves refactoring away from unions to a particular form of generics. The idea is to write your operations in terms of a “base” object type, mapped types over that base type, and generic indexed accesses into those types.
Your example makes this complicated because you have SomeUnion
and you don’t want to change it, and because one of the members of your union is not really involved in the relevant narrowing, and because the underlying data
is all of type string
with different keys, so it’s a mess. You need to derive the base type from SomeUnion
, and then rewrite SomeUnion
(or just the parts of it with data
) into a new type. It looks like this:
type DataMap = { [T in SomeUnion as "data" extends keyof T ? T["type"] : never]:
"data" extends keyof T ? T["data"] : never }
/* type DataMap = {
second: {
label: string;
};
third: {
url: string;
};
} */
type MyUnion<K extends keyof DataMap = keyof DataMap> =
{ [P in K]: { type: P, data: { [Q in keyof DataMap[P]]: string } } }[K]
Here DataMap
is a fairly straightforward object type which shows the Data
properties for each type
. Then MyUnion<K>
is a generic type which maps over DataMap
and indexes into it. It is a version of SomeUnion
(without first
) that explicitly represents its type generically. You can verify that MyUnion<"second">
is equivalent to SecondType
and that MyUnion<"third">
is equivalent to ThirdType
.
Now we can write a generic transformMyUnion
function which compiles as desired:
function transformMyUnion<K extends keyof DataMap>(value: MyUnion<K>): MyUnion<K> {
return {
...value,
data: objectKeys(value.data).reduce((data, key) => {
return {
...data,
[key]: replacer(data[key]),
};
}, value.data),
}
}
That’s because as a generic operation, key
is keyof DataMap[K]
and therefore data[keyof DataMap[K]]
is of type string
, and so the reduced thing is still of type DataMap[K]
, and thus {...value, data}
is of type MyUnion<K>
. And you can use transformMyUnion()
inside transformValue()
:
function transformValue(value: SomeUnion): SomeUnion {
return ('data' in value) ? transformMyUnion(value) : value
}
This works, and will prevent you from making some mistakes, but it’s so complex and therefore probably fragile in its own way. Sometimes the refactoring for microsoft/TypeScript#47109 is obviously an improvement, but in this case the cure seems worse than the disease. So I’d stick with type assertions or redundancy depending on whether you value expedience over type safety or not.
Playground link to code