1

In typescript, when doing assignment for regular function, the param in target function should be assignable to the param in the source function. For example, in the below code, the param "name" is type string in targetFunc, and the param name is type "abc"|"def" in srcFunc. string is a not subset of "abc"|"def", which means string is not assignable to "abc"|"def". Therefore, TS reports assignability errors as expected.

function targetFunc(name:string) {console.log(name)}
function srcFunc(name:"abc"|"def") {console.log(name)}
let t:typeof targetFunc = srcFunc;

It reports the following error as expected:
Type '(name: "abc" | "def") => void' is not assignable to type '(name: string) => void'.
  Types of parameters 'name' and 'name' are incompatible.
    Type 'string' is not assignable to type '"abc" | "def"'.(2322)

But for methods assignability between base class and child class, the same kind of error is not reported. For example, in below code, string is NOT assignable to type "abc"|"def", but TS doesn't report any error.

class Base {
    print(name:string) {console.log(`base:${name}`)}
}
class Child extends Base {
    print(name:"abc"|"def") {
        console.log(`Child:${name}`)
    }
}
let c:Child = new Child;
let b:Base = c;
b.print("apple")  //"apple" is NOT a subset of "abc"|"def", but TS doesn't report any error

For the same assignability error, why does TS report the error for regular function assignment, but does NOT report the same error for assignment between parent and child methods?

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
macyou
  • 99
  • 6
  • 1
    Method parameters are compared *bivariantly* which is unsafe but useful, while non-method function parameters are compared *contravariantly* (with `--strict` on), which is safer; see the answers to the linked questions for more information, and [this TS FAQ entry](https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-function-parameters-bivariant) (from before the time when any function parameters were checked covariantly) – jcalz Feb 25 '23 at 19:49

0 Answers0