【问题标题】:typescript: assert string is not part of a union打字稿:断言字符串不是联合的一部分
【发布时间】:2020-12-02 01:39:19
【问题描述】:

我想让 typescript 断言“新”字符串不是联合的一部分,字符串将被添加到现有集合。

我正在寻找一个独立的、独立的代码行,但这只是一个不错的选择。

所以,简单但人为的情况:

type FruitOptions = 'banana' | 'apple' | 'grape'
type NewFruitOption = 'pear'
// ^ being passed into a function ^

// Assert: FruitOptions does not contain NewFruitOption

我认为没有必要分享这个,但这是我正在寻求将这种技术应用到的实用功能:

// These are inferred generics (since they come after the = sign), do not pass them in.
export const renameKey = <
  OldKey extends keyof T,
  NewKey extends string, // should NOT already be keyof T
  T extends Record<string, unknown>
>(
  oldKey: OldKey,
  newKey: NewKey,
  userObject: T
): Record<NewKey, T[OldKey]> & Omit<T, OldKey> => {
  const { [oldKey]: value, ...common } = userObject

  return {
    ...common,
    ...({ [newKey]: value } as Record<NewKey, T[OldKey]>)
  }
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以检查NewKey 是否扩展了keyof T,如果是,请将参数类型设置为never,这样打字稿就会出错:

    newKey: NewKey extends keyof T ? never : NewKey
    

    当您更改此有效调用时:

    renameKey('lastName', 'clientLastName', formData)
    

    无效:

    renameKey('lastName', 'lastName', formData)
    

    您会在第二个'lastName' 上看到一个红色下划线:Argument of type 'string' is not assignable to parameter of type 'never'. ts(2345)。如果您尝试将密钥重命名为任何其他已存在的密钥,它也会失败:

    renameKey('lastName', 'dateOfBirth', formData)
    

    【讨论】:

      猜你喜欢
      • 2018-04-28
      • 2021-06-20
      • 2021-08-03
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 2018-12-07
      • 2019-02-22
      相关资源
      最近更新 更多