如何通过ESLint检测扩展运算符创建的数组类型一致性?
如何检测未指定类型数组中的元素类型不一致问题
我的ESLint配置如下:
extends: [ 'airbnb', 'airbnb/hooks', 'plugin:@next/next/recommended', 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended-requiring-type-checking', 'plugin:react/recommended', 'prettier', ],
比如下面的代码,用扩展运算符创建的array2包含两种不同类型的元素:
type sample = { id: number; name: string; }; const array1: sample[] = [{ id: 1, name: 'name1' }, { id: 2, name: 'name2' }, { id: 3, name: 'name3' }]; const array2 = [ ...array1, ...[{ id: 4, }] ];
因为没有指定array2的类型,TypeScript会将其推断为联合类型数组,不会触发报错,但这种情况很容易引发bug。请问有没有对应的ESLint规则可以检测这类数组类型不一致的问题?
有对应的ESLint规则可以解决这个问题,你可以使用@typescript-eslint/no-union-types规则,它能禁止代码中出现联合类型(包括数组元素的联合类型)。
在你的.eslintrc.js中添加以下规则配置:
rules: { '@typescript-eslint/no-union-types': ['error', { ignoreArrays: false }] }
默认情况下,这个规则会忽略数组的联合类型(ignoreArrays默认值为true),将其设为false后,当数组被推断为包含不同类型元素的联合类型时,ESLint就会抛出错误,提醒你存在类型不一致的问题。
如果不想完全禁止所有场景的联合类型,只是针对数组进行检测,这个配置刚好符合需求——它只会对数组的联合类型触发报错,不影响其他合法的联合类型使用。
内容的提问来源于stack exchange,提问作者Take
相关产品推荐
相关产品推荐

