-
Notifications
You must be signed in to change notification settings - Fork 30.5k
Closed
Description
- I have a question that is inappropriate for StackOverflow. (Please ask any appropriate questions there).
This is the typical way of defining an object with all optional members:
interface Options {
a?: boolean;
b?: string;
}However, because all members are optional, TypeScript will allow anything to match:
function init(options: Options) {
if (typeof options !== 'object') {
throw new Error();
}
}
// This isn't an error but is invalid.
init(1);Alternatively, the object could be defined as:
type StrictOptions = {
a: boolean;
b?: string;
} | {
a?: boolean;
b: string;
};and used like:
function strictInit(options: StrictOptions | object) {
if (typeof options !== 'object') {
throw new Error();
}
}
// TypeScript correctly flags this as an error.
strictInit(1);This results in an error from the compiler as you'd expect but can become very verbose. Would it be preferred to define options objects this way? Is there a more succinct way of doing this?
Edit:
Just realized I could simply define it as:
// All members not optional
interface Options {
a: boolean;
b: string;
}
type StrictOptions = Pick<Options, keyof Options>;function strictInit(options: StrictOptions | object) {
if (typeof options !== 'object') {
throw new Error();
}
}
strictInit(1); // Error
strictInit({}); // OK
strictInit({ a: true }); // OK
strictInit({ b: '' }); // OK
strictInit({ a: true, b: '' }); // OK
strictInit({ a: true, b: '', c: 1 }); // ErrorMetadata
Metadata
Assignees
Labels
No labels