Guy Gascoigne-Piggford
Guy Gascoigne-Piggford

Reputation: 689

Correctly declaring function return types in a typescript function declaration

I'm trying to get the correct declaration for a function to enforce the return type, and I can't seem to get it right.

In this example, I want the function updater to behave like the function updater2, but I want the simplicity if having a function declaration.

Can someone point out where I've gone wrong?

export type State = {
  name: string
};

export interface Updater {
  (old: State): State
}

const updater: Updater = (old) => {
  return {
    ...old,
    // this line generates no error
    foo: 1
  };
}

const updater2 = (old: State): State => {
  return {
    ...old,
    // this line correctly generates:
//    Type '{ foo: number; name: string; }' is not assignable to type 'State'.
//      Object literal may only specify known properties, and 'foo' does not exist in type 'State'.
    foo: 1
  };
}

Upvotes: 2

Views: 66

Answers (1)

Johnny Zabala
Johnny Zabala

Reputation: 2465

The problem here is Typescript type inference. It is analyzing the return type of your function and: { foo: number; name: string; } is assignable to { name: string; }. The name prop match.

To get the result that you want you need to help the compiler a little bit:

const updater: Updater = (old): State => {
  return {
    ...old,
    // this line generates no error
    foo: 1
  };
}

This way you are being specific about the intention. Your function has to return { name: string; }.

Upvotes: 1

Related Questions