理解 Typescript 中的类型和接口
界面
什么是接口:
主要特点:
**1.用于对象结构**
interface User {
username: string,
password: string,
email?: string // this is optional property
}**2.扩展支持:**
interface Address {
street: string,
city: string
}
interface User extends Address {
username: string,
password: string,
email?: string
}**3. 类可以实现接口:**
class Admin implements User {
username: string
password: string
email?: string
street: string
city: string
constructor(username: string, password:string, street:string, city:string, email?:string){
this.username = username;
this.password = password;
this.email = email || '';
this.street = street;
this.city = city;
};
}
var aAdmin = new Admin("user1", "123", "3/2 street", "hcmc");
console.log(aAdmin);输出:
Admin {
username: 'user1',
password: '123',
email: '',
street: '3/2 street',
city: 'hcmc'
}**4. 可以声明函数**
interface AddUser{
(name: string) : void;
}
const user : AddUser = (name) => console.log(`Hello ${name}`);类型
什么是类型:
主要特点:
**1. 任何类型的别名:**
type UserType = {
id: string,
name: string
}
type ID = string | number; //Union type**2. 支持交叉类型:**
type UserType = {
id: string,
name: string
}
type AddressType = {
street: string,
city: string,
}
type UserWithAddress = UserType & AddressType;**3. 支持元组:**
type Coordinates = [number, number]; const point: Coordinates = [10, 20];
**4. 无法重新打开:**
class AdminType extends UserType {
// ERROR: 'UserType' only refers to a type, but is being used as a value here.ts(2693)
}接口和类型之间的主要区别
何时使用接口与类型
使用界面:
interface User {
id: number;
name: string;
}使用类型:
type UserOrAdmin = User | Admin;
结合类型:
interface User {
id: number,
name: string,
email?: string
}
type Admin = User & {role: string};
const admin: Admin = {
id: 1,
name: 'Takie.Dang',
role: 'Administrator'
}