Home > front end >  Difference between => and : in Typescript
Difference between => and : in Typescript

Time:08-28

Wonder what's the difference between => and : in method header in Typescript? Thanks

  methodA: (
    fieldA: string,
  ) => interfaceA;

  methodA(
    fieldA: string
  ): interfaceA;

CodePudding user response:

There is a big difference. Methods are bivariant. It means, that it is not safe to use them. Consider this example


interface Bivariant {
    methodA(fieldA: string | number): void;
}


const bivariant: Bivariant = {
    methodA(fieldA: string) { // string is assignable to `fieldA` argument, not safe because it might be a number
        fieldA.includes('a')
    }
}

const foo = (arg: Bivariant) => {
    arg.methodA(42) // ok
}

foo(bivariant) // runtime error, no TS error

Playground

Please run this code. You will get a runtime error, because methodA in bivariant const expects a string argument and TS does not complain whereas according to Bivariant interface it might be also a number. Function foo, in turn, allows you to call arg.methodA with number.

Now, try to rewrite Bivariance interface with arrow function:

interface Bivariant {
    methodA:(fieldA: string | number) => void;
}

You will get an error.

This behavior is by design. Please see docs and docs.

Apart from that, check:

  • this article of Stephan Boyer,
  • this video of Titian-Cernicova-Dragomir 's talk and
  • my question where I listed all links about *-variance because this topic is very interesting.
  • here you can find my article with some examples of TS mutations
  • Related