MIT Weblab笔记 - Typescript
Introduction
TypeScript is a popular programming language that extends JavaScript by adding static types. Typescript catches errors at compile time rather than at runtime, making the code more reliable and easier to debug.
Syntax
Primitive Data Types
- number
- boolean
- string
- object
- undefined
- null
Declare a Type For a Variable
Define types of a variable using :.
let name: string = "John";
let age: number = 30;
let isStudent: boolean = false;
let message: string[] = ["1", "2", "3"];
let message: Array<string> = ["1", "2", "3"];Define a Type
type Color = "Red" | "Green" | "Blue";
let c: Color = "Red"; // can only be one of three colorstype myType = {
myProperty: string;
};
const newVariable: myType = {myProperty: "xxx"};
type User = {
_id: string;
name: string;
is_admin?: boolean;
};
const user: User = {
_id: "555";
name: "Eric";
};
export {User}- Denote optional params with ?
Typed Functions
const getComments = (id) => {
return [];
}const getComments = (id: string): Comment[] => {
return [];
}// add type for a function
type CommentProps = {
_id: string;
name: string;
handleAdd: () => void;
}MIT Weblab笔记 - Typescript
http://example.com/2024/07/24/MIT_Weblab/typescript/