使用共享类型对多个对象属性进行打字



经过一些打字稿研究和询问,我想出了以下多个属性的共享对象类型声明。

  • 问题 1:对于共享类型的多个道具,是否有更简单的方法可以做到这一点?
  • 问题2:如何解决最后两个示例?

打字稿游乐场

type StringProps = 'name' | 'surname' | 'color'
type NumberProps = 'age' | 'height'
//Simple type
type Simple = { [key in StringProps]: string };
const obj1: Simple = {
name: 'Agent',
surname: 'Smith',
color: 'red'
}
//Optional type
type Optional = { [key in StringProps]?: string };
const obj2: Optional = {
name: 'Agent'
}
//Combined optional type
type Combined = { [key in NumberProps]?: number } & Optional;
const obj3: Combined = {
name: 'Alex',
height: 2
}
// Property type change
type StringColor = Partial<Record<Exclude<NumberProps, 'color'>, number> & { color?: string }>
const obj4: StringColor = {
color: 'rgb'
}
// How to add any additional props with unknown keys?
type Additional = { [key: string]: boolean };
const obj5: Optional & Additional = {
color: 'rgb',
additional: true
}
// How to exclude Y prop from a type like this?
type XY = { x: string, y: number };
const obj6: XY = {
x: 'abc',
y: 1
}
type X = Record<Exclude<XY, 'y'>, number>
const obj7: XY = {
x: 'abc'
}

问题 1

类型看起来不错。您可以通过首先创建接口然后使用keyof来切换它,但这是一个品味问题。

问题2

对象5

对于obj5,您很可能必须将对象的索引签名更改为any,因为所有声明的特定属性都必须符合索引签名。

type Additional = { [key: string]: any };
const obj5: Optional & Additional = {
color: 'rgb',
additional: true
}

或者,您可以使用一些类型转换来处理此问题,因为您可以声明此类型。但是您不能创建它。因此,您可以将创建的对象类型转换为any然后返回到正确的类型,如下所示:

type Additional = { [key: string]: boolean };
const obj5: Optional & Additional = {
color: 'rgb',
additional: true
} as any as Optional & Additional;

我在另一个 Stackoverflow 问题中对这个主题给出了更详细的解释。

对象6:

对于obj6,您可以像这样简单地使用Omit助手:

type XY = { x: string, y: number };
const obj6: XY = {
x: 'abc',
y: 1
}
type X = Omit<XY, "y">
const obj7: XY = {
x: 'abc'
}

您创建类型的方法对我来说看起来不错。

至于问题二,为什么不使用省略来排除你不感兴趣的属性?例如

type X = Omit<XY, "y">
const obj7: X = {
x: 'abc'
}

至于obj5:

type Any= { [key: string]: any};
const obj5: Any = {
color: 'rgb',
additional: true
}
请注意,我没有使用"可选和任何">

,因为使用"任何"会使包含"可选"变得多余。

我想你可以稍微清理一下。

首先制作记录,然后修改它们,如果需要键,您可以随时在类型上调用keyof

type Simple = Record<'name' | 'surname' | 'color', string>
type Numbers = Record<'age' | 'height', number>
// if you need the keys
type SimpleKeys = keyof Simple // "name" | "surname" | "color"
type NumbersKeys = keyof Numbers // "age" | "height"
//Simple type
const obj1: Simple = {
name: 'Agent',
surname: 'Smith',
color: 'red'
}
//Optional type
type Optional = Partial<Simple>
const obj2: Optional = {
name: 'Agent'
}
//Combined optional type
type Combined = Partial<Numbers & Simple>;
const obj3: Combined = {
name: 'Alex',
height: 2
}
// Property type change
type StringColor = Partial<Omit<Simple, 'color'> & { color?: string }>
const obj4: StringColor = {
color: 'rgb'
}
// How to exclude Y prop from a type like this?
type XY = { x: string, y: number };
// Pick<XY, 'x'> or Omit<XY, 'y'>
const obj6: Pick<XY, 'x'> = {
x: 'abc',
}

最新更新