是否可以在Typescript中使用预定义的字符串文字类型定义类属性

时间:2017-09-27 16:13:20

标签: 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中实现我的目标吗?

1 个答案:

答案 0 :(得分:1)

这些常量都是具有恰好是字符串的值的变量。您正在尝试将它们用作类型。他们不是类型,所以要定义它。

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