Home > Enterprise >  Typescript array of ALL string literals types
Typescript array of ALL string literals types

Time:02-04

Is this possible to do

type Dessert = 'cake' | 'chocolate' | 'cookie'

const arrWithAllDessertTypes  = ['cake', 'chocolate'] // want TS to complain that it does contain `cookie`

I have googled and searched SO for the answer but it always talk about doing

const desserts = ['cake' , 'chocolate' , 'cookie'] as const

but I getting my Dessert type from an end-point response

CodePudding user response:

You can do this by using a const assertion

    const MyDessert = ['cake', 'chocolate', 'cookie'] as const;
    type Dessert = typeof MyDessert[number];  // "cake" | "chocolate" | "cookie" this defines the type you have on your first line

You can play with it in this TS playground

CodePudding user response:

I wrote my example with Dessert to make it generic. I did not find the exact solution, but found a way that will make TS tell me check my test files when some of the types are updated:

    import { IsEqual } from 'type-fest'


    const negativeStatusCases = ['pending', 'failed', 'cancelled', 'expired', 'in_progress'] as const
    negativeStatusCases.forEach((negativeStatus) => {
      describe(negativeStatus, () => {
        it('shows message with variant of "warning"', async () => {
          ...
        })
      })
    })

    it('covers all non `succeeded` status cases', () => {
      type Status = Awaited<ReturnType<typeof api.fetchPaymentStatus>>['status']
      type NegativeStatus = Exclude<Status, 'succeeded'>
      const allStatusCasesAreCovered: IsEqual<NegativeStatus, (typeof negativeStatusCases)[number]> = true
      expect(allStatusCasesAreCovered).toBe(true)
    })

hope it helps others

  • Related