This blog was last modified 468 days before.
Here this blog post will be considered as a quick note as I reading through the TypeScript Handbook.
This post will contain some easy-take mistakes and misconceptions about Typescript.
Basic Conceptions & Mechanisms
Interface and Type-alias
We all know in Typescript we could declare our own type structures by using Type-Alias or Interface.
The doc recommend us using Interface and only use Type-alias when we need some certain specified features provide by Type-alias.
The reason mentions is that interface usually has more detailed and well-formed error message compared to type alias.
Structure-focused & Duck types
Typescript actually focus and cares about the structure of the objects. that means it's possible that different types actually depict the same thing and work as the same.
type Point1 = { x: number, y: number };
type Point2 = { x: number, y: number };
interface Point3 {
x: number,
y: number
};
function printPoint(pointInfo: Point1) {
console.log(`<Point x=${pointInfo.x} y=${pointInfo.y}>`);
}
printPoint(pointinfo as Point2); // correct
printPoint(pointInfo as Point3); // also correct
As the example above, Point1
, Point2
and Point3
actually refer to the same structure and they could substitute each others.
This usually be called the Duck Type system.
Down-leveling
Typescript has the ability to general a lower version ECMAScript code (which could improve compatibility of your TypeScript project). You can even target the js output to ES3
standard.
Notice that most of major browser currently support ES5
standard, so in most cases you can feel free to target to ES5
version.
StrictMode
The most important ones are:
-
noImplicitAny: Do NOT allow type infers result in
any
. Which means all type should be properly marked / inferred. -
strictNullChecks As the names suggests, enabling this will require us to deal with
null
andundefined
explicitly in our code.
Also there exists a over-all param called strict
. You could add it to the command when using CLI, or add "strict": true
to your tsconfig.json
. This will turn on all strict check feature in default, but you have the right to opt-out some of them individually.
No comment