简体   繁体   中英

Typescript Object Class members are defined with interface

In Typescript, how do I define an Object Const, however make sure item members are in a interface?

Currently have this:

export const FrequencyType = {
  Weekly: { id: 1, code: 'Weekly', description: 'Weekly Description'},
  Annual: { id: 2, code: 'Annual', description: 'Annual Description'}
}

Intended:

with LookupVm Interface, this is giving error

export const FrequencyType = {
  Weekly: LookupVm: { id: 1, code: 'Weekly', description: 'Weekly Description'},
  Annual: LookupVm: { id: 2, code: 'Annual', description: 'Annual Description'}
}

Reference:

export interface LookupVm {
  id: number;
  code: string;
  description: string;
}

Create interface like the below

export default interface LookupVm{
id:number,
code:string,
description: string
}

Then use it in the const like

export const FrequencyType :{
Weekly: LookupVm,
Annual: LookupVm
}= {
  Weekly: { id: 1, code: 'Weekly', description: 'Weekly Description'},
  Annual: { id: 2, code: 'Annual', description: 'Annual Description'}
}

Here is one solution, However Hitech solution will work also

export const FrequencyType = {
  Weekly: { 
    id: 1, 
    code: 'Weekly', 
    description: 'Weekly Description' 
  } as LookupVm,
  Annual: { 
    id: 2, 
    code: 'Annual', 
    description: 'Annual Description' 
  } as LookupVm
}

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