Course repository: https://github.com/moonhighway/intro-to-typescript
Required: Node.js >= v18.0.0
Recommended: Visual Studio Code (with GitHub Copilot disabled)
Setup
If you've already cloned the repository, bring it up-to-date:
git pull
Then install dependencies by running:
npm install
let myFavoriteFood = 'Pozole Rojo';let myFavoriteFood: string = 'Pozole Rojo';unknown, any
string, number, bigint, boolean, symbol
null, undefinednever
const boat: {
name: string;
length: number;
atSea: boolean;
} = {
name: "S. S. Minnow",
length: 30,
atSea: false,
};interface Boat {
name: string;
length: number;
atSea: boolean;
}type Boat = {
name: string;
length: number;
atSea: boolean;
};? for optional properties
readonly for immutable properties
const populations: number[] = [
8537673,
2140526,
3769495
];Array typeconst populations: Array<number> = [
8537673,
2140526,
3769495
];const highestTemperature: [string, number] = [
'Vancouver',
34.4
];Problems panelGo to Type Definition'async function return types: Promise<Type>
|
string | numbertypeof type guard===
instanceof type guardtry...catch statement, TypeScript infers errors as any
catch block can only be declared as any or unknown
unknown as it gives us type safety
interface Comment {
id: string;
body: string;
}
interface ApprovedComment extends Comment {
approved: boolean;
}interface X extends Y { ... }&
type StringArray = {
[index: number]: string;
}
type NumberDictionary = {
[index: string]: number;
}When you don't know the names of an object's properties, but know what the types should be.
typeof Type Operator
export and import
.d.ts
@types packages (DefinitelyTyped project)
Share it here and let's debug it together!
Things which are generic.
Functions function someFunction(){...}
Classes class SomeClass(){...}
Types type SomeType = {...}Functions function someFunction<Type>(){...}
Classes class SomeClass<Type>(){...}
Types type SomeType<Type> = {...}Adding a type parameter makes the "thing" generic! ✨
Partial<Type>
Required<Type>
Readonly<Type>
ReadonlyArray<Type>
Pick<Type, Keys>
Omit<Type, Keys>
Record<Keys, Type>
...and more!
class Country {
name;
code;
}class Country {
readonly name;
private code;
}class Country<CodeType> {
name;
code: CodeType;
}// @ts-ignore Suppress any type errors on next line.
// @ts-expect-error Error if next line doesn't have error.
// @ts-nocheck Disable type checking for a file.