英文:
TypeScript does not recognize properties when instantiating interface array
问题
我已经创建了以下界面,我想在我的自定义Angular组件中实现。
界面:
export interface Device {
constructor(
deviceID: string,
deviceName: string,
deviceModel: string,
manufactureYear: string,
deviceOS: string
);
}
自定义组件:
import { Component, OnInit} from "@angular/core";
import { Device } from "src/shared/interfaces/device";
@Component({
selector: 'device-dashboard',
templateUrl: './device-dashboard.component.html',
styleUrls: ['./device-dashboard.component.less']
})
export class DeviceDashBoardComponent implements OnInit{
constructor() {}
devices: Device[] = [
{
deviceID: "12345",
deviceName: 'name',
deviceModel: 'model',
manufactureYear: '2015',
deviceOS: 'Ubuntu 22.04',
},
];
ngOnInit(): void { }
}
不幸的是,TS编译器不断突出显示第一个属性,并在我悬停在它上面时显示以下错误消息。
Type '{ deviceID: string; deviceName: string; deviceModel: string; manufactureYear: string; deviceOS: string; }' is not assignable to type 'Device'.
Object literal may only specify known properties, and 'deviceID' does not exist in type 'Device'.
英文:
I have created the following interface that I want to implement in my custom Angular component.
Interface:
export interface Device {
constructor(
deviceID: string,
deviceName: string,
deviceModel: string,
manufactureYear: string,
deviceOS: string
);
}
Custom component
import { Component, OnInit} from "@angular/core";
import { Device } from "src/shared/interfaces/device";
@Component({
selector: 'device-dashboard',
templateUrl: './device-dashboard.component.html',
styleUrls: ['./device-dashboard.component.less']
})
export class DeviceDashBoardComponent implements OnInit{
constructor() {}
devices: Device[] = [
{
deviceID: "12345",
deviceName: 'name',
deviceModel: 'model',
manufactureYear: '2015',
deviceOS: 'Ubuntu 22.04',
},
];
ngOnInit(): void { }
Unfortunately, the TS compiler keeps highlighting the first property and shows the following error message when I hover over it.
Type '{ deviceID: string; deviceName: string; deviceModel: string; manufactureYear: string; deviceOS: string; }' is not assignable to type 'Device'.
Object literal may only specify known properties, and 'deviceID' does not exist in type 'Device'.
答案1
得分: 1
以下是翻译的内容:
扩展 @about14sheep 的回答
正确的接口应该是
export interface Device {
deviceID: string;
deviceName: string;
deviceModel: string;
manufactureYear: string;
deviceOS: string;
}
编辑(感谢 @VLAZ):你当前的接口只定义了一个名为 constructor 的方法,但没有公共属性。
英文:
To extend the answer of @about14sheep
The correct Interface would be
export interface Device {
deviceID: string;
deviceName: string;
deviceModel: string;
manufactureYear: string;
deviceOS: string;
}
Edit (thanks to @VLAZ): Your current interface just defines a method called constructor - but no public attributes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论