【问题标题】:I want to protect type as const with other type on typescript我想用打字稿上的其他类型将类型保护为 const
【发布时间】:2021-07-05 17:37:57
【问题描述】:

如果有更合适的标题,请告诉我。

例如,我在 AB 类型中添加 C。我希望在 ABSentences 中出现类型检查错误。

typescript playground

示例代码

type AB = {
    A?: any
    B?: any
}

const ABSentences: { [key in keyof Required<AB>]: string } = {
    A: 'this is A.',
    B: 'this is B.',
} as const

我想使用type AB 来保护ABSentences 的密钥。

你有什么好主意吗?

ABSentences的实际类型

const ABSentences: {
    A: string;
    B: string;
}

期望类型的 ABSentences

const ABSentences: {
    A: 'this is A.';
    B: 'this is B.';
}

【问题讨论】:

    标签: typescript


    【解决方案1】:
    const ABSentences = {
        A: 'this is A.',
        B: 'this is B.',
    } as const
    

    如果您使用as const,只需删除显式类型注释

    【讨论】:

    • 比如我在AB类型中加了C。我希望 ABSentences 中的类型检查错误。
    猜你喜欢
    • 2017-05-18
    • 2021-03-25
    • 2018-06-08
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2021-04-19
    • 2015-06-24
    • 2021-03-11
    相关资源
    最近更新 更多