Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Type alias for function signature not as strict as direct annotations

Tags:

typescript

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?

like image 333
severin Avatar asked Nov 19 '25 09:11

severin


1 Answers

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

like image 112
Aleksey L. Avatar answered Nov 21 '25 00:11

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!