prefer-as-const
注意:此规则是
recommended
规则集的一部分。在
deno.json
中启用完整规则集{ "lint": { "tags": ["recommended"] } }
使用 Deno CLI 启用完整规则集
deno lint --tags=recommended
建议使用 const 断言 (as const
) 而不是显式指定字面量类型或使用类型断言。
当声明一个新的原始字面量类型变量时,有三种方式
- 添加显式类型注解
- 使用普通类型断言 (例如
as "foo"
或<"foo">
) - 使用 const 断言 (
as const
)
此 lint 规则建议使用 const 断言,因为它通常会带来更安全的代码。有关 const 断言的更多详细信息,请参阅官方手册。
无效
let a: 2 = 2; // type annotation
let b = 2 as 2; // type assertion
let c = <2> 2; // type assertion
let d = { foo: 1 as 1 }; // type assertion
有效
let a = 2 as const;
let b = 2 as const;
let c = 2 as const;
let d = { foo: 1 as const };
let x = 2;
let y: string = "hello";
let z: number = someVariable;