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?