打字稿继承从数组值返回

时间:2021-06-13 12:29:18

标签: typescript

假设我有一个存储变量的文件,其中包含一个具有如下常量值的数组:

// file: variables.ts

/**
 * An array that stores the image types
 *
 * **The order is important! Sorted from less important to most important**
 */
export const IMAGE_TYPES: Readonly<string[]> = ['small', 'medium', 'large'];

现在,当我将鼠标悬停在 IDE 中时,我会得到一个简单的返回类型,如下所示: const IMAGE_TYPES: readonly string[]

如果我想以相同的顺序添加返回类型,我可以这样做:

// file: variables.ts

/**
 * An array that stores the image types
 *
 * **The order is important! Sorted from less important to most important**
 */
export const IMAGE_TYPES: Readonly<['small', 'medium', 'large']> = ['small', 'medium', 'large'];

现在悬停是:const IMAGE_TYPES: readonly ['small', 'medium', 'large'] 这是我想要的

然而,这违反了 DRY 原则并导致双重类型,有没有一种方法可以推断出彼此的值或类型?数组的值永远不会改变,并且顺序应始终与 JSDoc 中显示的相同。

1 个答案:

答案 0 :(得分:1)

您可以像这样获得相同的类型 (readonly ['small', 'medium', 'large']):

export const IMAGE_TYPES = ['small', 'medium', 'large'] as const;

有关详细信息,请参阅const assertions