Narrowing with in & instanceof
Në shqip: Ngushtimi me in dhe instanceof
ShpjegimiSQ
"noto" in kafsha kontrollon nëse objekti ka atë veti, dhe x instanceof Date nëse është krijuar nga ajo klasë. Pas kontrollit, TypeScript e ngushton tipin automatikisht.
EnglishEN
"swim" in animal checks whether the object has that property, and x instanceof Date whether it was created from that class. After the check, TypeScript narrows the type automatically.
Si ta mendosh
Si të pyesësh „a ke krahë?“ për të ditur nëse është zog.
Lexoje në anglisht
Like asking “do you have wings?” to tell whether it's a bird.
Shembull koditypescript
type Peshk = { noto(): void }; type Zog = { fluturo(): void };
function leviz(k: Peshk | Zog) {
if ("noto" in k) k.noto(); else k.fluturo();
}