将新属性添加到接口



我有一个如下所示的 API interface。我无法向其添加任何属性,因为它不受我的控制。但是我需要包含布尔属性,例如isPhotoSelected: boolean = false;。你能告诉我怎么做吗?

export interface LibraryItem {
    id: string;
    photoURL: string;
    thumbnailURL: string;
    fileName: string;
}

定义一个implements interfaceclass

export class DtoLibraryItem implements LibraryItem{
    //need to declare all the properties of the interface here
    isPhotoSelected: boolean
}

你试过声明合并吗? 这似乎更符合您的要求,而不是您当前接受的答案:

// import from module
import { LibraryItem } from 'librarymodule'; 
// locally augment the module's interface declaration  
declare module './playground' {
  export interface LibraryItem {
    isPhotoSelected: boolean
  }
}
// use it
const libtaryItem: LibraryItem = {
  id: 'id',
  photoURL: 'https://example.com/photo.jpg',
  fileName: 'fileName.ext',
  thumbnailURL: 'https://example.com/thumbnail.jpg',
  isPhotoSelected: true
}

希望有帮助;祝你好运!

最新更新