在学习了一些 TypeScript 并询问过之后,我得出了以下用于多个属性的共享对象类型声明。
- 问题 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'
}
omit
:type X = Omit<XY, "y">
- pascalpuetz