-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Type Guard syntax for array #1587
Comments
A type guard class Message {
value: string;
}
function saySize(message: Message | Message[]) {
if (message instanceof Array) {
return message.length; // message of type Message[] here
}
} we would want the type guard to remove the type Now, the reason you don't get an error when the |
As is, it's legitimately possible for an object to both be an
To make this kind of type guard safe, there would need to be some way to "seal" the |
Right, since interfaces are structural we can technically never trust an |
To make this kind of type guard safe, there would need to be some way to "seal" the Message type so it can't be extended, or perhaps make it nominal so that an object that merely has a value: string field isn't considered a Message. While this is true, people write type guards in JavaScript all the time which are equally susceptible to this sort of break. We should do what we can to help them since the pattern isn't going away. |
Surely you can just assume, that in interface ArrayMessage extends Array<string>, Message {}
function foo (in: Messaage | Message[]) {
if (message instanceof Array) {
//message is of type Message and Message[] here, since both are valid?
}
} As for interfaces, I vote you only expect what's defined on the interface: interface mything {
a: string
}
interface myotherthing {
b: number
}
function foo(athing: mything|myotherthing) {
if (typeof athing.a !== "undefined") {
//Here we typeguard to mything, even though the object can have both an a and a b, we've specified that we're interested in the a at the moment.
//possibly you could (for interfaces) allow checks of other variables (e.g. the existance of b) within the type guard, but not accesses unless within a type-guarded statement
if (typeof athing.b !== "undefined") {
//Here athing is a mything that has a b of some kind (but is not necessarily a myotherthing)
console.log(athing.b); //valid.
}
}
} |
Perhaps a bug, the following does not work although I think its the right syntax:
However, the following does work.
Note to team: Feel free to edit this query to increase its life. original report: #805 (comment).
The text was updated successfully, but these errors were encountered: