簡體   English   中英

是否可以在Typescript中使用預定義的字符串文字類型定義類屬性

[英]Is it possible to define a class property with predefined string literal types in Typescript

我正在嘗試在Typescript中實現以下目標,但始終遇到編譯錯誤:

const AUDIENCE_ALL_COMPANY = 'all_company'
const AUDIENCE_SITE = 'site'
const AUDIENCE_DEPARTMENT = 'department'

export class Post {
  readonly audienceType: AUDIENCE_ALL_COMPANY | AUDIENCE_SITE | AUDIENCE_DEPARTMENT

   ...
}

是否可以在Typescript中實現我的目標?

這些常量都是變量,其值恰好是字符串。 您正在嘗試將它們用作類型。 它們不是類型,請對其進行定義。

const AUDIENCE_ALL_COMPANY = 'all_company';
const AUDIENCE_SITE = 'site';
const AUDIENCE_DEPARTMENT = 'department';

type AUDIENCE_ALL_COMPANY = typeof AUDIENCE_ALL_COMPANY;
type AUDIENCE_SITE = typeof AUDIENCE_SITE;
type AUDIENCE_DEPARTMENT = typeof AUDIENCE_DEPARTMENT;

export class Post {
    readonly audienceType: AUDIENCE_ALL_COMPANY | AUDIENCE_SITE | AUDIENCE_DEPARTMENT;
}

暫無
暫無

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

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