-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Type Guard for function property leads to overloading #14820
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
That might seem surprising, but it is correct. Your type guard refines the type of class X {
hasValFunc(): this is X & { valFunc(): number } {
return !!this.valFunc;
}
valFunc?: () => number = () => {
return 1;
};
} this changes the semantics of your class, making the function a per instance property instead of a method on |
@aluanhaddad // --strictNullChecks
type XData = {
flags: {
hasProp1: boolean,
},
prop1?: number,
}
class X {
protected data: XData;
hasProp1(): this is this & { getProp1(): number } {
return this.data.flags.hasProp1
}
hasProp1Alternative(): this is this & { data: { prop1: number } } {
return this.data.flags.hasProp1
}
getProp1() {
return this.data.prop1
}
}
const x = new X()
if (x.hasProp1()) {
x.getProp1().toFixed() // error
}
if (x.hasProp1Alternative()) {
x.getProp1().toFixed() // error
x.data.prop1.toFixed() // ok, but this breaks down encapsulation
} Here are a few main reasons:
Maybe there is alternative way, but in my example TypeScript doesn't provide me what I want (via both Simple summary: |
This is not the intended use of type guards as they stand today. Moreover, the intersection behavior you are seeing is consistent with the semantics of the type operator; a intersecting two signatures result in overloads. I believe you are looking for something like #11117. |
TypeScript Version: 2.2.1
I'm confused with type guard and function property.
Type Guard can redefine property from
number | undefined
tonumber
(useful for strictNullChecks mode)But for functions such type guard has added overloading.
Code
Expected behavior:
No error in the last case
Actual behavior:
In the last case
valFunc()
has two signatures:(): number | undefined
(): number
The text was updated successfully, but these errors were encountered: