Cài đặt môi trường Typescript
Tham khảo bài viết Tóm tắt Kiến thức Cơ bản về TypeScript cho Người Mới Bắt Đầu
npm install -g typescript
tsc --version
npm install -g ts-node
ts-node --version
Tạo File add.ts
function addNumbers(a: number, b: number) {
return a + b;
}
const sum: number = addNumbers(10, 15)
console.log('Tính Tổng 2 số : ' +sum);
Biên dịch add.ts sang file add.js
tsc add.ts
Chạy file add.ts
ts-node add.ts
tsconfig.json
tsc --init
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"rootDir": "./src",
"skipLibCheck": true,
"noImplicitAny": false
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
Trong TypeScript, các kiểu dữ liệu cơ bản bao gồm:
// 1. boolean
let isDone: boolean = false;
// 2. number
let decimal: number = 6;
// 3. string ""
let color: string = "blue";
// 4. array
let list: number[] = [1, 2, 3];
let listText: string[] = ["1", "2", "3"];
let list2: Array<number> = [1, 2, 3];
// Array<number> == number[]
// 5.tuple
let x: [string, number, boolean];
x = ["hello", 10, true]; // Đúng
// 6 enum
enum Color {
Red, // 0
Green, // 1
Blue, // 2
}
let c: Color = Color.Red;
console.log(c);
// 7 any
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // cũng đúng
// 8 void
function warnUser(): void {
console.log("This is my warning message");
}
// 9 null undefined
let u: undefined = undefined;
let n: null = null;
//10 object
let obj: object = { name: "John", age: 30 };
Type & Interface
// 1 type alias
type Student = {
id: number;
name: string;
age: number;
classes: string[];
address: {
street: string;
city: string;
zipcode: string;
};
};
// 2 Interface
interface StudentFPOLY {
id: number;
name: string;
age: number;
classes: string[];
}
//3 Ke thua
type StudentKy6 = Student & {
kyHoc: number;
doneProject: boolean;
};
interface StudentFPOLYKy6 extends StudentFPOLY {
kyHoc: number;
doneProject: boolean;
}
// 4. Union: type1 | type2| ...
type Ky6 = number | string | boolean;
const student: StudentKy6 = {
id: 1,
name: "Alice",
age: 20,
classes: ["Typescript", "React"],
address: {
street: "123 Main St",
city: "Wonderland",
zipcode: "12345",
},
kyHoc: 6,
doneProject: true,
};
Create Project React + Typescript
npm create vite@latest
project_name
React
Typescript
cd project_name
npm i
npm i axios
npm run dev
App.tsx
import { useEffect, useState } from "react";
import "./App.css";
import axios from "axios";
type Product = {
title: string;
image: string;
description: string;
};
function App() {
const [products, setProducts] = useState<Product[]>([]); // Array Product
const getAllProduct = async () => {
const { data } = await axios.get("https://fakestoreapi.com/products");
setProducts(data);
};
useEffect(() => {
getAllProduct();
}, []);
return (
<>
{products.map((product, index) => (
<div key={index} className="card" style={{ width: "18rem" }}>
<img
src={product.image}
className="card-img-top"
alt="..."
width={"100px"}
/>
<div className="card-body">
<h5 className="card-title">{product.title}</h5>
<p className="card-text">{product.description}</p>
<a href="#" className="btn btn-primary">
Go somewhere
</a>
</div>
</div>
))}
</>
);
}
export default App;