我有这件事
enum OfferType {
  Apartment = 'apartment',
  House = 'house',
  Room = 'room',
  Hotel = 'hotel',
}当您键入属性值时,应使用哪些选项。何时应用每种方法
1)
{
  type: type as OfferType
}{
  type: OfferType[type as 'apartment' | 'house' | 'room' | 'hotel']
{发布于 2022-09-11 11:07:08
我将假设type是string类型的,因为您是从TypeScript代码的范围之外接收到的。
在这种情况下,我不会使用您展示的两个选项,因为它们都是假设是一个有效的OfferType,这不是一个可靠的假设。(但如果你想做出这样的假设,没有理由使用第2条,只需使用#1;操场链接。)
相反,我会使用类型谓词函数或类型断言函数,它们都将type的类型缩小到OfferType ,而在运行时检查这个假设。
类型谓词:
function isOfferType(value: string): value is OfferType {
    return (Object.values(OfferType) as string[]).includes(value);
}用法:
if (isOfferType(type)) {
    obj = { type };
} else {
    // Handle the fact it isn't one类型断言函数:
function assertIsOfferType(value: string): asserts value is OfferType {
    if (!(Object.values(OfferType) as string[]).includes(value)) {
        throw new Error(`"${value}" is not a valid OfferType`);
    }
}用法:
assertIsOfferType(type);
const obj = { type };https://stackoverflow.com/questions/73678644
复制相似问题