所有字符串文本类型的TypeScript数组

zqry0prt  于 2023-02-10  发布在  TypeScript
关注(0)|答案(2)|浏览(132)

是否可以做到:

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

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

我已经在谷歌上搜索了这么一个答案,但它总是谈论这样做:

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

但是我从端点响应中获得了Dessert类型。

wgeznvg7

wgeznvg71#

您可以通过使用常量Assert来完成此操作

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

你可以在这个TSPlayground玩它

j5fpnvbx

j5fpnvbx2#

我用Dessert写了我的例子,使它通用。我没有找到确切的解决方案,但找到了一种方法,当一些类型更新时,TS会告诉我检查我的测试文件:

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)
    })

我希望它能帮助其他人🙂

相关问题