js 接口实现
接口实现的基本概念
在JavaScript中,接口通常指的是定义对象或类应该遵循的结构或契约。虽然JavaScript本身没有像TypeScript那样的显式接口语法,但可以通过多种方式模拟接口行为。
使用对象字面量模拟接口
通过定义一个对象字面量来规定对象必须包含的属性和方法:
const userInterface = {
name: '',
age: 0,
greet: function() {}
};
function createUser(user) {
if (!user.name || !user.age || !user.greet) {
throw new Error('Invalid user object');
}
return user;
}
使用类模拟接口
通过类继承或混入模式实现接口功能:

class IUser {
constructor() {
if (new.target === IUser) {
throw new Error('Cannot instantiate interface');
}
}
greet() {
throw new Error('Method not implemented');
}
}
class User extends IUser {
greet() {
console.log('Hello!');
}
}
使用TypeScript接口
在TypeScript中可以直接使用接口语法:
interface IUser {
name: string;
age: number;
greet(): void;
}
class User implements IUser {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, ${this.name}`);
}
}
使用鸭子类型检查
通过检查对象是否具有特定属性来验证接口实现:

function isUser(user) {
return 'name' in user &&
'age' in user &&
typeof user.greet === 'function';
}
const user = {
name: 'Alice',
age: 25,
greet() {
console.log('Hi!');
}
};
if (isUser(user)) {
user.greet();
}
使用Symbol实现私有接口
通过Symbol创建唯一键来实现更严格的接口控制:
const IUser = {
greet: Symbol('greet')
};
class User {
[IUser.greet]() {
console.log('Private greeting');
}
publicGreet() {
this[IUser.greet]();
}
}
使用Proxy实现接口验证
通过Proxy对象在运行时验证接口实现:
const userValidator = {
get(target, prop) {
if (prop === 'name' && !target[prop]) {
throw new Error('Name is required');
}
return target[prop];
}
};
const user = new Proxy({}, userValidator);
user.name = 'Bob'; // 正常工作
user.age = 30; // 正常工作






