Suppose I have a function that requires a specific interface
interface Foo {
foo: number;
bar: number;
baz?: number;
buz?: number;
}
const doFoo = (params: Foo) => { /* ... */ };
I also possess a constant containing default values for some properties of Foo
:
const BASE_PROPERTIES = {
foo: 42,
baz: 9001,
};
doFoo({
...BASE_PROPERTIES,
bar: -1000
});
This works as expected. However, I am curious if there is a way to indicate that BASE_PROPERTIES
includes specific parts of Foo
. This would enhance code editing and clarify the purpose of the constant. Essentially, similar to an automated Pick<>
.
I could attempt
const BASE_PROPERTIES: Partial<Foo> = { /* ... */ }
However, this results in an error for foo
when used in the spread operator because of
Type 'number | undefined' is not assignable to type 'number'
. Although I could resolve it with as any
or as Foo
, it comes at the risk of potentially forgetting to include all necessary properties.
Another option is to use pick
const BASE_PROPERTIES: Pick<Foo, 'foo' | 'baz'> = { /* ... */ }
Yet, this approach involves manual maintenance which can be cumbersome, especially for large objects, and does not provide intellisense support when adding new properties, thereby partially defeating its original purpose.
Is there a method in TypeScript to suggest that an object should adhere to an interface schema, while allowing the compiler to determine how the constant aligns with the interface?