To start, ensure that all properties in the PropsInterface
are nullable.
export enum SomeProperties {
prop1,
prop2,
prop3
};
interface PropsBase {
[SomeProperties.prop1]: number;
[SomeProperties.prop2]: boolean;
[SomeProperties.prop3]: string;
}
type NullableRecord<T> = {
[Prop in keyof T]: T[Prop] | null
}
type PropsInterface = NullableRecord<PropsBase>
Once that is done, you can assign null
as a property type.
let props: PropsInterface = {
[SomeProperties.prop1]: null,
[SomeProperties.prop2]: null,
[SomeProperties.prop3]: null
}
However, there might be an issue with the following code:
const fieldToUpdate = {
field: SomeProperties.prop1,
value: 123
}
props[fieldToUpdate.field] = fieldToUpdate.value;
The problem arises because fieldToUpdate.field
is inferred as an enum
, expecting all keys, while you only need SomeProperties.prop1
.
To resolve this, simply use the as const
assertion.
const fieldToUpdate = {
field: SomeProperties.prop1,
value: 123
} as const
props[fieldToUpdate.field] = fieldToUpdate.value;
Here is the complete code snippet:
export enum SomeProperties {
prop1,
prop2,
prop3
};
interface PropsBase {
[SomeProperties.prop1]: number;
[SomeProperties.prop2]: boolean;
[SomeProperties.prop3]: string;
}
type NullableRecord<T> = {
[Prop in keyof T]: T[Prop] | null
}
type PropsInterface = NullableRecord<PropsBase>
// Example of usage.
// An object with properties that can be updated individually.
let props: PropsInterface = {
[SomeProperties.prop1]: null,
[SomeProperties.prop2]: null,
[SomeProperties.prop3]: null
};
const fieldToUpdate = {
field: SomeProperties.prop1,
value: 123
} as const
props[fieldToUpdate.field] = fieldToUpdate.value;
Playground