Open DanKim0213 opened 11 months ago
As I wrote in the cheatsheet of typescript, the below example works just as if we had used an anonymous object type.
interface Point {
x: number;
y: number;
}
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
Another example is that when we narrow types:
type Fish = { swim: () => void };
type Bird = { fly: () => void };
declare function getSmallPet(): Fish | Bird;
function isFish(pet: Fish | Bird): pet is Fish {
return 'swim' in pet;
}
// ---cut---
// Both calls to 'swim' and 'fly' are now okay.
let pet = getSmallPet()
// **Fish or Bird**
if (isFish(pet)) {
pet.swim(); // Fish
} else {
pet.fly(); // Bird
}
We can figure out which type of pet
is by in
operator.
Keep in mind that these three JavaScript operators:
typeof
is used for primitive valuesinstanceof
is used for instances of classes constructed with new
keywordin
is used for objects with specific propertiesType Guard
needed instead of intanceof
?Type
and Interface
should I use since they are interchangeable?You should consider consistency and augmentation. - Effective Typescript, item 13
If you are working in a codebase that consistently uses interface
, stick with interface
. The same goes for Type
.
Else:
interface
.Type
since declaration merging, which is only available in interface
, is likely to be a mistake.A. Same
TypeScript