MST

星途 面试题库

面试题:TypeScript接口扩展的基础实现

假设有一个基础接口`Person`,包含`name`和`age`属性。请通过接口扩展创建一个新接口`Student`,使其继承`Person`接口,并新增`studentId`属性,然后编写一个函数,接受`Student`类型的参数并打印出所有属性。请给出完整代码。
25.2万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义Person接口
interface Person {
  name: string;
  age: number;
}

// 定义Student接口,继承Person接口并新增studentId属性
interface Student extends Person {
  studentId: number;
}

// 定义函数,接受Student类型参数并打印所有属性
function printStudent(student: Student) {
  console.log(`Name: ${student.name}, Age: ${student.age}, Student ID: ${student.studentId}`);
}

// 测试
const myStudent: Student = {
  name: "Alice",
  age: 20,
  studentId: 12345
};
printStudent(myStudent);

上述代码首先定义了Person接口,包含nameage属性。然后通过interface Student extends Person扩展出Student接口,新增了studentId属性。最后定义printStudent函数,接受Student类型参数并打印其所有属性,同时进行了简单的测试。如果是在其他语言中实现类似功能,代码结构和语法会有所不同,比如Java:

// 定义Person接口
interface Person {
    String getName();
    int getAge();
}

// 定义Student接口,继承Person接口并新增getStudentId方法
interface Student extends Person {
    int getStudentId();
}

// 实现Student接口的类
class StudentImpl implements Student {
    private String name;
    private int age;
    private int studentId;

    public StudentImpl(String name, int age, int studentId) {
        this.name = name;
        this.age = age;
        this.studentId = studentId;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public int getAge() {
        return age;
    }

    @Override
    public int getStudentId() {
        return studentId;
    }
}

// 定义打印方法
class Printer {
    public static void printStudent(Student student) {
        System.out.println("Name: " + student.getName() + ", Age: " + student.getAge() + ", Student ID: " + student.getStudentId());
    }
}

// 测试
public class Main {
    public static void main(String[] args) {
        Student student = new StudentImpl("Bob", 22, 67890);
        Printer.printStudent(student);
    }
}

在Java中,通过接口定义方法签名,类实现接口来具体实现功能。Student接口继承Person接口并新增getStudentId方法,StudentImpl类实现Student接口,Printer类定义printStudent方法打印Student对象属性,在main方法中进行测试。