假设我有一个存储变量的文件,其中有一个常数值数组,如下所示:
// 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中显示的相同。
您可以获得相同的类型(readonly ['small', 'medium', 'large']
(,如下所示:
export const IMAGE_TYPES = ['small', 'medium', 'large'] as const;
有关更多信息,请参阅const断言