Let's illustrate this question with a couple of examples:
interface MyInput {
reqString: string,
reqNumber: number,
optString?: string
}
const defaultValues: Partial<MyInput> = {
reqString: "hello",
optString: "goodbye"
};
// An error occurs for the reqNumber property here:
// Types of property 'reqString' are incompatible
// Type 'string | undefined' is not assignable to 'string'
const inputObject: MyInput = {
...defaultValues,
reqNumber: 5
};
The first example helps me with type hints while constructing the defaultValues
object, ensuring I define properties in MyInput
. However, using Partial<MyInput>
makes all properties optional, leading to inputObject
not being recognized as having all required properties in MyInput
, even though it does.
Here's another scenario with the same concept:
interface MyInput {
reqString: string,
reqNumber: number,
optString?: string
}
// No type hints are set to match MyInput
const defaultValues = {
reqString: "hello",
optString: "goodbye"
};
// This no longer produces an error
const inputObject: MyInput = {
...defaultValues,
reqNumber: 5
};
In this setup, inputObject
fully adheres to MyInput
without any compilation issues. However, the drawback is the absence of type hinting for defaultValues
.
I understand that I could use the type
Pick<MyInput, 'reqString' | 'optString'>
for defaultValues
, but updating it when adding more properties becomes cumbersome.
Is there a method to dynamically type defaultValues
to represent a subset of MyInput
(with type safety) and also be acknowledged within inputObject
as defining the missing required properties?