簡體   English   中英

Typescript Object Class 成員用接口定義

[英]Typescript Object Class members are defined with interface

在 Typescript 中,如何定義 Object 常量,但要確保項目成員在接口中?

目前有這個:

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

故意的:

使用 LookupVm 接口,這會出錯

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

參考:

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

創建如下界面

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

然后在 const 中使用它

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

這是一種解決方案,但是 Hitech 解決方案也可以使用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM