vitest/prefer-expect-type-of Style
作用
强制使用 toBeTypeOf 而不是 expect(typeof ...).toBe(...)。
为什么这不好?
expect(typeof value).toBe(type) 可以工作,但写法别扭,而且失败信息很差。 Vitest 内置的 toBeTypeOf 匹配器执行的是相同的 typeof 比较,但 API 更清晰,错误输出也更好。
示例
以下是此规则的错误代码示例:
js
test("type checking", () => {
expect(typeof "hello").toBe("string");
expect(typeof 42).toBe("number");
expect(typeof true).toBe("boolean");
expect(typeof {}).toBe("object");
expect(typeof (() => {})).toBe("function");
expect(typeof Symbol()).toBe("symbol");
expect(typeof 123n).toBe("bigint");
expect(typeof undefined).toBe("undefined");
});以下是此规则的正确代码示例:
js
test("type checking", () => {
expect("hello").toBeTypeOf("string");
expect(42).toBeTypeOf("number");
expect(true).toBeTypeOf("boolean");
expect({}).toBeTypeOf("object");
expect(() => {}).toBeTypeOf("function");
expect(Symbol()).toBeTypeOf("symbol");
expect(123n).toBeTypeOf("bigint");
expect(undefined).toBeTypeOf("undefined");
});如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["vitest"],
"rules": {
"vitest/prefer-expect-type-of": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["vitest"],
rules: {
"vitest/prefer-expect-type-of": "error",
},
});bash
oxlint --deny vitest/prefer-expect-type-of --vitest-plugin版本
此规则已于 v1.44.0 中添加。
