【发布时间】: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