-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
Bug Report
🔎 Search Terms
- predicate
- type predicate
- type predicate return
🕗 Version & Regression Information
- This is NOT a crash
- This changed between versions ______ and _______
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
- I was unable to test this on prior versions because _______
⏯ Playground Link
Playground link with relevant code
💻 Code
interface Animal {
name: string;
}
interface Bird extends Animal {
wingSpan: string;
}
/**
* Asserts that an animal is of type T if condition is true for that animal.
*/
function isAnimalOfType<T extends Animal>(animal: Animal, condition: (animal: T) => boolean): animal is T {
return condition(animal as T);
}
function isBird(animal: Animal) {
return isAnimalOfType<Bird>(animal, (bird) => Boolean(bird.wingSpan));
}
function getWingspan(bird: Bird) {
return bird.wingSpan;
}
const animals = [{ name: "a" }, { name: "a", wings: "3ft" }] as Animal[];
function checkAnimals(animals: Animal[]) {
return animals.map(animal => {
console.log(animal);
if (isBird(animal)) {
console.log(getWingspan(animal));
}
})
}
🙁 Actual behavior
The call to getWingspan
shows an error saying Argument of type 'Animal' is not assignable to parameter of type 'Bird'
.
🙂 Expected behavior
The function isAnimalOfType
already asserts that the Animal will be of type T. So, why does isBird
not automatically assert that?
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created