TypeScript
替JavaScript追加了如型別定義等功能
最終仍會編譯成JavaScript
會在編譯時進行檢查,藉此提昇程式品質
例如呼叫函式或帶入時的型別是否正確
通常使用.ts副檔名
會將.ts檔編譯為.js檔
React的副檔名則為.tsx
$ npm install -g typescript
$ tsc hello.ts
Node.js
$ npm install -g ts-node typescript
修改 package.json
"scripts":{ "ts-node": "ts-node" },
$ npm run ts-node
code:typescript
class InvalidDateFormatError extends Error {}
class DateIsInTheFutureError extends Error {}
function parse(birthday: string): Date {
let date = new Date(birthday)
if (isNaN(date.getTime())) {
throw new InvalidDateFormatError("Enter a date in the form YYYY/MM/DD");
}
if (date.getTime() > Date.now()) {
throw new DateIsInTheFutureError("Are you a timelord?");
}
return date;
}
try {
const date = parse("2025/01/01");
console.log("Date is", date.toISOString());
} catch (e) {
if (e instanceof InvalidDateFormatError) {
console.error(e.message)
} else if (e instanceof DateIsInTheFutureError) {
console.warn(e.message)
} else {
throw e;
}
}
code:typescript
class InvalidDateFormatError extends Error {}
class DateIsInTheFutureError extends Error {}
function parse(
birthday: string
): Date | InvalidDateFormatError | DateIsInTheFutureError {
let date = new Date(birthday)
if (isNaN(date.getTime())) {
throw new InvalidDateFormatError("Enter a date in the form YYYY/MM/DD");
}
if (date.getTime() > Date.now()) {
throw new DateIsInTheFutureError("Are you a timelord?");
}
return date;
}
const result = parse("2025/01/01");
if (result instanceof InvalidDateFormatError) {
console.error(e.message)
} else if (result instanceof DateIsInTheFutureError) {
console.warn(e.message)
} else {
console.log("Date is", result.toISOString());
}