Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当使用枚举值作为接口属性名称时,Typescript编译器生成未使用的变量_Typescript - Fatal编程技术网

当使用枚举值作为接口属性名称时,Typescript编译器生成未使用的变量

当使用枚举值作为接口属性名称时,Typescript编译器生成未使用的变量,typescript,Typescript,当在接口中将枚举用作属性名称时,typescript编译器(tsc版本3.2.2)添加一条require语句,而当将枚举用作属性值时,它不添加该语句: // ifce.ts import { PROPS } from './props'; export interface ISomething { someKey: PROPS; } 假设我在文件中定义了枚举: // props.ts export enum PROPS { A = 'PROP_A', B = 'PROP_B',

当在接口中将枚举用作属性名称时,typescript编译器(tsc版本3.2.2)添加一条
require
语句,而当将枚举用作属性值时,它不添加该语句:

// ifce.ts
import { PROPS } from './props';

export interface ISomething {
  someKey: PROPS;
}
假设我在文件中定义了枚举:

// props.ts
export enum  PROPS {
  A = 'PROP_A',
  B = 'PROP_B',
}
以及在第二个文件中使用枚举指定属性名称的接口:

// ifce.ts
import { PROPS } from './props';

export interface ISomething {
  [PROPS.A]: string;
}
tsc ifce.ts
生成变量
props\u 1

"use strict";
exports.__esModule = true;
// ifce.ts
var props_1 = require("./props");
另一方面,如果枚举用作属性值:

// ifce.ts
import { PROPS } from './props';

export interface ISomething {
  someKey: PROPS;
}
输出不会产生任何变量:

// ifce.js
"use strict";
exports.__esModule = true;

有没有一种方法可以防止在使用属性名时生成这个未使用的变量,就像使用属性值一样?

我认为这是一个编译器错误。通常,当导入未在表达式中使用且仅在类型中使用时,将省略导入。这在中有记录

例如,由于
PROPS.A
仅在类型注释中使用,因此此代码不会发出导入代码

import { PROPS } from './props';

let A : PROPS.A
如果我们在表达式中使用
PROPS
enum,则不会省略导入,例如,此代码将生成导入代码:

import { PROPS } from './props';

let  A = PROPS.A

计算属性是一种特殊的构造,因为尽管它们是一种类型,但是计算的属性名称必须是表达式(一种唯一符号类型的文字类型的简单表达式,但仍然是表达式),并且相信这是造成(错误地认为在我看来)编译器考虑导入的原因。 作为一种解决方法,您可以使用一个间接级别,可以声明枚举成员类型的

const
,并在接口声明中使用它

import { PROPS } from './props';

declare const A: PROPS.A
export interface ISomething {
    [A]: string;
}
这将防止编译器将导入代码作为
道具发出。A
仅用于
A
的类型注释,然后该常量用于接口定义。由于这只是一个接口,所以const在运行时不存在这一事实并不重要

注意您可以使用该技巧获取整个枚举:

import { PROPS } from './props';

declare const LOCAL_PROPS: typeof PROPS
export declare interface ISomething {
    [LOCAL_PROPS.A]: string;
}
注意