首页 文章

“接口”类型中不存在属性?

提问于
浏览
1

我是Typescript的新手 . 我试图使用接口作为数组类型 . 我按顺序构造我的文字对象,虽然我仍然得到这个错误:

输入'{id:number; Headers :字符串;图像:字符串;单词:string;描述:字符串; } []'不能赋值为'IWordList []' . 输入'{id:number; Headers :字符串;图像:字符串;单词:string;描述:字符串; }'不能赋值为'IWordList' . 对象文字只能指定已知属性,'IWordList'类型中不存在'id' .

Notice that the case isn't about 'id' itself, but it is if I added any addtioal property, I get the same error

IWordList.ts

export interface IWordList{
    id : number;
    title : string;
    image : string;
    words : string;
    description : string;
}

wordlistsdata.service.ts

import { Injectable } from '@angular/core';
import { IWordList } from './IWordlist';

@Injectable()
export class WordlistsdataService {

  constructor() { }

  private allWordLists : IWordList[] = 
  [
      {
          id : 1,
          title : "Animals",
          image : "/src/app/images/wordlists/animals_background.jpg",
          words : "cat,elephant,cow,duck",
          description : "sdadasd"
      },
      {   
          id : 2,
          title : "Jobs",
          image : "/src/app/images/wordlists/jobs_background.jpg",
          words : "engineer,farmer,artist,programmer",
          description : "sdadasd"
      }

    ]

  public getWordList() : IWordList[]{
    return this.allWordLists;
  }

  public getOneWordList(id : number) : string[] {
    return 
  }
}

3 回答

  • 0

    我只是将你的代码复制到一个Plunker中,它运行得很好 . 你可以在这里看到我的代码:https://plnkr.co/edit/sxcYl5v5jBlfzZ31fHLd?p=preview

    看看你是否也可以从那里运行它 .

    啊......但是这个工具需要我粘贴代码......即使你已经在上面...所以这里是AppModule:

    @NgModule({
      imports: [ BrowserModule ],
      declarations: [ App ],
      providers: [ WordlistsdataService ],
      bootstrap: [ App ]
    })
    export class AppModule {}
    
  • -2

    我有同样的错误 . 它出现在我的构建表中,但不在Linter中,它可以检测到这些错误 . 所以我决定重新启动构建,并得到一个新的错误,指向我创建了一个没有抛出错误的属性的对象(在你的情况下为“id”) . 有趣的是,Linter错过了那个实际错误 . 我修复了这段代码,以便定义“id”,并再次启动构建 . 这次它没有错误 .

  • 0

    试试这个:

    export interface IWordList{
        id ?: number;
        title : string;
        image : string;
        words : string;
        description : string;
    }
    

    ? 运算符允许您使事物可选 .

相关问题