Typescript 使用共享类型为多个对象属性编写类型脚本

Typescript 使用共享类型为多个对象属性编写类型脚本,typescript,Typescript,经过一些typescript研究和询问,我为多个属性提出了以下共享对象类型声明 问题1:对于共享类型的多道具,有没有更简单的方法? 问题2:如何解决最后两个示例? 您创建类型的方法在我看来很好 至于问题二,为什么不使用排除您不感兴趣的财产?e、 g type X = Omit<XY, "y"> const obj7: X = { x: 'abc' } 请注意,我没有使用Optional&Any,因为使用Any会导致包含可选的冗余项。问题1: 这些类型看起来不错。您可以通过先创

经过一些typescript研究和询问,我为多个属性提出了以下共享对象类型声明

问题1:对于共享类型的多道具,有没有更简单的方法? 问题2:如何解决最后两个示例?
您创建类型的方法在我看来很好

至于问题二,为什么不使用排除您不感兴趣的财产?e、 g

type X = Omit<XY, "y">
const obj7: X = {
   x: 'abc'
}
请注意,我没有使用Optional&Any,因为使用Any会导致包含可选的冗余项。

问题1:

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

问题2

obj5:

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

type Additional = { [key: string]: any };
const obj5: Optional & Additional = {
   color: 'rgb',
   additional: true
}
或者,您可以通过一些类型转换来处理这个问题,因为您可以声明这个类型。但不允许您创建它。因此,您可以将创建的对象类型转换为任意类型,然后返回到正确的类型,如下所示:

type Additional = { [key: string]: boolean };
const obj5: Optional & Additional = {
   color: 'rgb',
   additional: true
} as any as Optional & Additional;
type XY = { x: string, y: number };
const obj6: XY = {
   x: 'abc',
   y: 1
}

type X = Omit<XY, "y">
const obj7: XY = {
   x: 'abc'
}
我在另一篇文章中详细解释了这个话题

obj6:

对于obj6,您只需像下面这样使用省略辅助对象:

type Additional = { [key: string]: boolean };
const obj5: Optional & Additional = {
   color: 'rgb',
   additional: true
} as any as Optional & Additional;
type XY = { x: string, y: number };
const obj6: XY = {
   x: 'abc',
   y: 1
}

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

我想你可以把这个清理一下

首先做记录,然后修改它们,如果您需要密钥,您可以随时调用类型上的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',
}

谢谢,但更多的是关于从多个属性对象中排除一些道具,只需使用省略即可:type X=Omit@pascalpuetz谢谢,现在只剩下obj5问题:@RTW我为obj5解决方案添加了一个类型安全的替代方案。