After some typescript studying and asking around i come up with the following shared object types declaration for multiple properties.
- Question 1: is there simplier way to do it for multiple props wih shared types?
- Question 2: how to resolve last two examples?
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'
}