typescript - 打字稿对象或类:当类实现接口时不可能有额外的属性?
问题描述
我想知道为什么当这个类实现一个接口时,它不可能在打字稿类中实现额外的属性或函数......它说:...... "Object literal may only specify known properties and "FirstName" does not exist in type persInterface"
..我认为在java中它也可以实现其他道具或函数,implementas接口只是该类的强制子集,而不是限制..这种行为在 Typescript 中是否正常?
interface persInterface {
lastName: String,
sayHello: () => number
}
var person: persInterface = {
FirstName:"Tom",
lastName:"Hanks",
sayHello: ()=>{ return 10} ,
};
解决方案
您谈论实现接口的类,但是您的示例代码没有这样做,它只有一个对象文字。使用该对象字面量,您已将其定义为完全是 persInterface,这就是为什么在尝试添加不属于 persInterface 的属性时会出现错误的原因。
如果您确实尝试拥有一个实现接口的类,那么您可以做您想做的事,而不会出现任何类型错误(操场链接):
interface persInterface {
lastName: string,
sayHello: () => number
}
class Person implements persInterface {
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
sayHello(): number {
return 10;
}
}
const person = new Person('tom', 'hanks');
如果您正在使用文字,那么您需要创建一个从基本接口扩展的接口并指定额外的属性是什么:
interface persInterface {
lastName: string,
sayHello: () => number
}
interface persPlusPlus extends persInterface {
lastName: string
}
const person: persPlusPlus = {
firstName:"Tom",
lastName:"Hanks",
sayHello: ()=> { return 10; } ,
};
推荐阅读
- sql - Oracle 日期操作
- python - 使用 Dask 处理大型压缩 csv 文件
- android - 使用 Bazel 和 j2objc 在 iOS 和 Android 之间共享代码
- swift - 如何在 Swift 中创建多个块实例?
- python - 仅为功能创建 django 应用程序
- java - Windows 10 任务栏位置
- node.js - Google/Firebase 云功能的速率限制?
- php - 刮掉破碎的图像并加入它们以制作用于电子书创作的完整图像
- android - Appium 无法在 android 设备上识别和滚动元素
- c - 检查 char 数组是否包含特定单词