& 多个类型集合的交集
| 多个类型集合的并集
使用type定义
type Admin = {
name: string;
privileges: string[];
}
type Employee = {
name: string;
startDate: Date;
}
type ElevatedEmployee = Admin & Employee;
使用interface定义
interface Admin {
name: string;
privileges: string[];
}
interface Employee {
name: string;
startDate: Date;
}
interface ElevatedEmployee extends Admin, Employee{}
使用定义的类型
let ee: ElevatedEmployee = {
name:'max',
privileges:['create-admin'],
startDate:new Date()
}
编译后的js
let ee = {
name: 'max',
privileges: ['create-admin'],
startDate: new Date()
};
使用type 定义任意类型
type Combinable = string | number;
typeGuard: 保护代码在运行时不报错
function printEmployeeInformation(emp: ElevatedEmployee) {
console.log('name'+ emp.name)
//判断属性是否存在
if('privileges' in emp){
console.log('employee '+ emp.privileges)
}
if('startDate' in emp){
console.log('startDate '+ emp.startDate)
}
}
printEmployeeInformation(ee)
检验对象的某个属性是否存在
https://dmitripavlutin.com/check-if-object-has-property-javascript/
// @errors: 2493
class Car {
driver(){
console.log('driving...')
}
}
class Truck{
driver(){
console.log('driving is truck')
}
loadCargo(amount: number){
console.log('loading cargo' + amount)
}
}
type Vehicle = Car | Truck;
const v1 = new Car();
const v2 = new Truck();
function useVehicle(vehicle: Vehicle) {
vehicle.driver();
if(vehicle instanceof Truck){
vehicle.loadCargo(1000)
}
// if('loadCargo' in vehicle){
// vehicle.loadCargo(1000)
// }
}
useVehicle(v1);
useVehicle(v2);
//output
// [LOG]: "driving..."
// [LOG]: "driving is truck"
// [LOG]: "loading cargo1000"
网友评论