Reputation: 122182
I have an interface
interface Foo {
name: string
subject: string
body: string
}
And a function that takes in Foo | {}
where I destructure the properties and do things with them if they are non-empty
const doStuff = ({body, subject, name}: Foo | {}) => {
const errors = [
body?.trim() && `body`,
subject?.trim() && `subject`,
name?.trim() && `name`,
].filter(x => x);
setErrors(errors)
...
}
the destructuring is not compiling because well...it might be an object without those properties. How on earth do I tell typescript that its cool, an I want those properties to be undefined
in that case without resorting to @ts-ignore
or any
?
Upvotes: 1
Views: 279
Reputation: 134521
Rather than using the type Foo | {}
, use Partial<Foo>
instead. Partial<T>
makes all members optional which is effectively what you're trying to do.
const doStuff = ({ body, subject, name }: Partial<Foo>) => {
...
};
Upvotes: 1