首页 > 解决方案 > 我想用打字稿上的其他类型将类型保护为 const

问题描述

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

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

打字稿游乐场

示例代码

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.

你有什么好主意吗?

缺席的实际类型

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

期望类型的 ABSentences

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

标签: typescript

解决方案


const ABSentences = {
    A: 'this is A.',
    B: 'this is B.',
} as const

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


推荐阅读