I am currently working on implementing a mapped type that has some required parameters and some optional ones.
While I have successfully implemented the required parameters, I am facing issues with utilizing the optional ones.
type Foo = { foo: string }
const A_FIELD_REQ = ['x', 'y'] as const
const A_FIELD_OPT = ['z'] as const
const B_FIELD_REQ = ['x', 'y', 'z'] as const
const B_FIELD_OPT = [] as const
type QueryA = {
type: 'a'
fields: { [field in typeof A_FIELD_REQ[number]]: Foo | undefined }
}
type QueryB = {
type: 'b'
fields: { [field in typeof B_FIELD_REQ[number]]: Foo | undefined }
}
type Query = {
id: string
} & (QueryA | QueryB)
const myQueries: Query[] = [
{
id: '0',
type: 'a',
fields: {
x: { foo: '' },
y: { foo: '' },
},
},
{
id: '1',
type: 'a',
fields: {
x: undefined, // valid
y: { foo: '' },
},
},
{
id: '2',
type: 'b',
fields: {
x: { foo: '' },
y: { foo: '' },
z: { foo: '' },
},
},
]
Modifying my types
My goal is to be able to include optional parameters within the same key fields
of my Query
type, similar to a basic z?: Foo | undefined
.
const myQueries = [
{
id: '0',
type: 'a',
fields: {
x: { foo: '' },
y: { foo: '' },
},
},
{
id: '1',
type: 'a',
fields: {
x: undefined, // valid
y: { foo: '' },
},
},
{
id: '2',
type: 'b',
fields: {
x: { foo: '' },
y: { foo: '' },
z: { foo: '' },
},
},
{
id: '3',
type: 'a',
fields: {
x: { foo: '' },
y: { foo: '' },
z: { foo: '' }, // !!! optional parameter !!!
}
}
]