TS 是 TypeScript 的縮寫,是一種由微軟開發的開源編程語言,它是 JavaScript 的一個超集,為 JavaScript 添加了類型系統和對 ES6+ 的支持。以下是關于 TypeScript 的詳細介紹:
一、特點
類型系統:TypeScript 引入了類型注解,允許開發者為變量、函數參數、返回值等添加類型信息。這有助于在編譯階段發現潛在的類型錯誤,提高代碼的健壯性和可維護性。例如:
let message: string = "Hello, TypeScript!"; function add(a: number, b: number): number {return a + b; }
在 TypeScript 中,
type
和interface
都可以用來定義復雜數據類型,它們各有特點和適用場景,以下是詳細介紹:
二、使用?type
?定義復雜數據類型
- 基本語法:
type TypeName = {property1: Type1;property2: Type2;// ...
};
- 定義對象類型:
type Person = {name: string;age: number;address: {street: string;city: string;};
};
- 定義聯合類型:
type StringOrNumber = string | number;
- 定義交叉類型:?
type Employee = {employeeId: number; } & Person;
- 定義泛型類型:?
type Container<T> = {value: T; };
三、使用?
interface
?定義復雜數據類型 - 基本語法:?
interface InterfaceName {property1: Type1;property2: Type2;// ... }
- 定義對象類型:?
interface Person {name: string;age: number;address: {street: string;city: string;}; }
- 定義類類型:?
interface Person {name: string;age: number;greet(): void; } class Student implements Person {name: string;age: number;constructor(name: string, age: number) {this.name = name;this.age = age;}greet() {console.log(`Hello, my name is ${this.name}`);} }
type
?與?interface
?的區別與選擇 區別:
type
是類型別名,可以為任何類型定義一個新的名字,包括基本類型、聯合類型、交叉類型等;而interface
主要用于定義對象類型或類類型。interface
可以被類實現(implements
),而type
不行。interface
可以繼承其他接口,而type
不行。type
定義的類型可以使用交叉類型(&
)來組合多個類型,而interface
只能繼承一個接口。
選擇:
如果需要定義一個對象類型或類類型,并且希望使用繼承或類實現,建議使用
interface
。如果需要定義聯合類型、交叉類型或泛型類型,或者需要為復雜類型定義別名,建議使用
type
。在實際開發中,可以根據具體需求和團隊編碼規范來選擇使用
type
或interface
。
四、 函數類型
在 TypeScript 中,函數類型用于描述函數的參數類型和返回值類型。你可以通過類型別名(type
)或接口(interface
)來定義函數類型。?
interface Api {foo(): void;bar(str: string): string;
}function test(api: Api) {api.foo();const result = api.bar("hello");console.log(result);
}// 調用 test 函數
test({foo() {console.log('ok');},bar(str: string) {return str.toUpperCase();}
});
五、字面量與nullish類型
// 字面量類型:功能:輸出一段文字(參數1),參數2決定文字的對齊方式
function printText(text: string, alignment: "left" | "right" | "center") {console.log(text, alignment);
}printText("Hello", "left");
printText("Hello", "center");// nullish 類型 null undefined
function test(x?: string | null) {// if (x !== null && x !== undefined)// console.log(x.toUpperCase()); // 錯誤:x 可能為 null 或 undefinedconsole.log(x?.toUpperCase()); // 正確:使用可選鏈
}test("hello");
test(null);
test();
六、泛型
interface Ref<T> {value: T;
}const r1: Ref<string> = { value: 'hello' };
const r2: Ref<number> = { value: 123 };
const r3: Ref<boolean> = { value: true };function test1(n: string) {return { value: n };
}function test2(n: number) {return { value: n };
}function ref<T>(n: T): Ref<T> {return { value: n };
}const v1 = ref("hello"); // Ref<string>
const v2 = ref(123.3333); // Ref<number>
console.log(v2.value.toFixed(2)); // 輸出: 123.33
?七、class語法
一個基本的類定義包括類名、屬性(成員變量)和方法(成員函數):
class Person {// 類屬性(成員變量)firstName: string;lastName: string;// 構造函數constructor(firstName: string, lastName: string) {this.firstName = firstName;this.lastName = lastName;}// 類方法(成員函數)fullName(): string {return `${this.firstName} ${this.lastName}`;}
}
繼承
TypeScript 支持類的繼承,可以使用 extends
關鍵字來實現:
class Employee extends Person {employeeId: number;constructor(firstName: string, lastName: string, employeeId: number) {super(firstName, lastName); // 調用父類的構造函數this.employeeId = employeeId;}work(): string {return `${this.fullName()} is working`;}
}
訪問修飾符
TypeScript 提供了三種訪問修飾符:
public
:公共的,可以在任何地方訪問。private
:私有的,只能在類內部訪問。protected
:受保護的,可以在類內部和子類中訪問。class Person {private name: string;constructor(name: string) {this.name = name;}public getName(): string {return this.name;} }
抽象類
抽象類是不能被實例化的類,通常用作基類:
abstract class Animal {abstract makeSound(): void;move(): void {console.log("Moving");} }class Dog extends Animal {makeSound(): void {console.log("Bark");} }
靜態成員
類可以包含靜態屬性和方法,這些成員屬于類本身,而不是類的實例:
class Utils {static pi: number = 3.14;static calculateCircleArea(radius: number): number {return Utils.pi * radius * radius;} }
類表達式
類也可以作為表達式定義,這在定義匿名類時非常有用:
const Animal = class {makeSound() {console.log("Some generic sound");} };const dog = new Animal(); dog.makeSound(); // 輸出: Some generic sound
類類型
類本身可以作為類型使用:
let person: Person; person = new Person("Alice", "Smith");
類與接口
類可以實現接口,接口定義了類必須遵循的結構:
interface Greeting {greet(): string; }class Hello implements Greeting {greet(): string {return "Hello";} }