简体   繁体   中英

Add a new property to Interface

I have an API interface like below. I cannot add any property to it since it is not under my control.But I need to include boolean property like isPhotoSelected: boolean = false; to it. Can you tell me how to do that?

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

Define a class that implements the interface .

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

Have you tried declaration merging ? That seems to be more in line with what you're asking for than your currently accepted answer:

// 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
}

Hope that helps; good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM