0

Say I have declared a type:

type MyCustomType = {
    key1: 'value1' | 'value2'
    key2: boolean
    key3: number
}

I am trying to write some code that will check if all values for a given object of type "MyCustomType" have defined values. e.g.

function validate(input: MyCustomType): boolean {
    const fieldsToCheck = ['key1', 'key2', 'key3'] as const;
    return fieldsToCheck.every((key) => !!input[key])
}

I can manually define 'fieldsToCheck' like the example, but ideally I would like a way to generate the array from the type definition. Conversely I would be okay with declaring the array, then defining the type relative to that array.

what do?

yo conway
  • 207
  • 1
  • 5
  • 1
    You can't generate values from types, as the type system in TypeScript is [erased](https://www.typescriptlang.org/docs/handbook/2/basic-types.html#erased-types). You can generate a type from a value, although this will just give you key types and not the full object type. You can maybe make a dummy object and then derive both `MyCustomType` and `fieldsToCheck` from it like [this](https://tsplay.dev/NDkeRw). Does that meet your needs? Or am I missing something? – jcalz Apr 14 '22 at 03:25
  • honestly it almost meets my needs and is a fun creative answer. The one gotcha for my specific scenario is that key1: string is actually not a string, but a union of a few specific string values. – yo conway Apr 14 '22 at 03:30
  • 1
    Well, `key1: string` is what’s in the question. If you have an unmet need then you might want to [edit] the question to specify it. – jcalz Apr 14 '22 at 03:51
  • I see you edited the question (but without "@jcalz" mentioning me I don't get notified of such things). Does [this approach](https://tsplay.dev/NdoEvw) work for you? It's getting sillier. Personally I'd probably just do something like [this](https://tsplay.dev/N7O5qN) where you have to maintain redundant info but you get a warning if you make a mistake. Let me know which, if any, of these approaches you want me to write up as an answer. – jcalz Apr 14 '22 at 13:14

1 Answers1

0

You can use:

const fieldsToCheck = Object.keys(input);

This will return a string[] of the keys from your input object