我只想在值未定义的情况下将属性设置为值,否则我不想设置属性.

我通常是这样处理这种情况的:

  const payload: UpdateDistributionCommandInput = {
    Id: cloudFrontId,
    DistributionConfig: {
      ...distribution.DistributionConfig,
      Aliases: {
        Items: modifiedAliasItems,
        Quantity: modifiedAliasItems.length
      }
    }
  }

  if (typeof distribution.ETag === "string") {
    payload.IfMatch = distribution.ETag;
  }

  const updateDistributionCommand = new UpdateDistributionCommand(payload)

我觉得有点冗长和凌乱.有没有更简短的语法来描述这个场景,或者用其他方式来描述这个场景?

推荐答案

如果payload.ifMatch被定义为ifMatch?: string,那么行为取决于exactOptionalPropertyTypes编译器选项.

考虑:

interface Payload {
  ifMatch?: string
}

With 100,这将起作用:

const payload: Payload = {
  ifMatch: undefined
}

我们也将:

const payload: Payload = {}
payload.ifMatch = undefined

With 100,你会发现错误:

const payload: Payload = {
  //  ^^^^^^^
  // Type '{ ifMatch: undefined; }' is not assignable to type 'Payload' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
  //  Types of property 'ifMatch' are incompatible.
  //    Type 'undefined' is not assignable to type 'string'.(2375)
  ifMatch: undefined
}

payload.ifMatch = undefined
//^^^^^^^^^^^^^
// Type 'undefined' is not assignable to type 'string' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the type of the target.(2412)

Playground Link(在TS配置菜单中切换exactOptionalPropertyTypes)

Typescript相关问答推荐

TypScript如何在 struct 上定义基元类型?

APP_INITIALIZER—TypeError:appInits不是函数

TypeScript泛型参数抛出错误—?&#"' 39;预期"

数组文字中对象的从键开始枚举

未在DIST中正确编译TypeScrip src模块导入

如何将所有props传递给React中的组件?

为什么我的一个合成函数不能推断类型?

迭代通过具有泛型值的映射类型记录

对于始终仅在不是对象属性时才抛出的函数,返回Never

专用路由组件不能从挂钩推断类型

自动通用回调

将超类型断言为类型脚本中的泛型参数

将布尔值附加到每个对象特性

如何通过属性名在两个泛型数组中找到匹配的对象?

映射类型不是数组类型

如何使用useSearchParams保持状态

React Context TypeScript错误:属性';firstName';在类型';iCards|iSearch';

如何在Vuetify 3中导入TypeScript类型?

在ts中获取级联子K类型?

Typescript 从泛型推断类型