How to write a general function that acts upon keys in an object while maintaining type safety?

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật