2021年5月7日星期五

How can a TypeScript forEach, infer the types of a union, and change the return type

We want to take a document type and mutate some of it's fields and then return the new document with the new types. We want to determine the fields to mutate based on an array of values (collectionDataFields in the example below).

type AllDocuments = {      __typename: 'cat'      a: '123',      b: '123',      z: 'xyz'  } | {      __typename: 'dog'      a: '123',      c: '123',      z: 'xyz'  }    const collectionDateFields = {      cat: ['a', 'b'],      dog: ['a', 'c']  } as const    export const useDatesToLuxon = (document: AllDocuments) => {    const dateFields = collectionDateFields[document.__typename]      dateFields.forEach((field) => {      document[field] = parseInt(document[field])    })    return document  }    

In the example, dateFields is typed as readonly ["a", "b"] | readonly ["a", "c"] but the individual field comes in as any.

The document is returned as the AllDocuments even though we want it to have the field with the changed type (as a number).

TS Playground Example

https://stackoverflow.com/questions/67442388/how-can-a-typescript-foreach-infer-the-types-of-a-union-and-change-the-return May 08, 2021 at 06:33AM

没有评论:

发表评论