I'm trying to simplyfy signatures in TypeScript using a type alias:
interface State {
value: string;
error: string;
}
type Reducer = (value: string) => (state: State) => State;
const setValue: Reducer = value => state => ({
...state,
value,
unknownProperty: "Hello"
});
I would expect this to fail since I'm trying to set a property that doesn't exist.
When I do this, it does fail:
const setValue2 = (value: string) => (state: State): State => ({
...state,
value,
unknownProperty: "Hello"
});
with error message: Object literal may only specify known properties, and 'unknownProperty' does not exist in type 'State', which is what I want.
What is the difference? Why does one compile, but the other not? How can I enforce type safety like the second example using a separate definition like in the first example?
The difference is that in the first case the produced function type (implicitly resolved) is compatible with type Reducer. Have a look at this example:
let x = () => ({name: "Alice"});
let y = () => ({name: "Alice", location: "Seattle"});
x = y; // OK
However in the second case the return type is explicitly specified (state: State): State, here "Object literal may only specify known properties" comes into play
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With