I've got an anonymous object with a TypeScript typed property. Something like this:
type Foo = {
exists: true;
bar: string;
};
doSomething({
foo: {
exists: true,
bar: 'baz',
} as Foo,
});
I'd like to type protect the foo
property so if type Foo
ever changes in the future (e.g. gets a new property), then the TypeScript compiler will warn me. While these cause compiler errors:
doSomething({
foo: {
exists: 'string', // Incorrect type
bar: 'baz',
} as Foo
});
doSomething({
foo: {
say: 'hello', // Not enough overlap with Foo
bar: 'baz',
} as Foo
});
This doesn't cause a type error, even though exists
is missing:
doSomething({
foo: {
bar: 'baz',
} as Foo
});
Likewise, this also doesn't cause a type error:
doSomething({
foo: <Foo>{
bar: 'baz',
},
});
The only way I can force a type error when a property of Foo
is missing is this:
const foo: {foo: Foo} = {
foo: {
bar: 'baz',
},
};
doSomething(foo);
...but that requires me to unnecessarily create a local variable simply for the purpose of type safety. Is there a way to type protect the property of an anonymous object?
Note: doSomething()
's parameter accepts any
and doesn't enforce any type requirements, otherwise I could rely on doSomething
enforcing the type.
CodePudding user response:
TypeScript 4.9 will introduce the satisfies
operator.
doSomething({
foo: {
bar: 'baz',
} satisfies Foo,
});
Until then, you may use another function to validate foo
at compile time.
const validFoo = (foo: Foo) => foo
doSomething({
foo: validFoo({
bar: 'baz',
}),
});