Я ищу правило/плагин Eslint, чтобы запретить этот вид выражения:
if (!something) {
return // can be anything here, but it's often a return
}
// Or the other way equivalent
if (something) {
// Use the variable here because we checked it is not null nor undefined
}
if (someBoolean) {
// This one is okay since it's a boolean
}
Проблема в том, что в некоторых случаях, если значение оценивается на ложный, но не неопределенный/нулевой, это не то, что мы хотели:
const something: number | undefined = 0
if (!something) {
return // Will return as 0 is falsy, but we actually wanted to check if it was undefined but forgot about this case!
}
< /code>
Поэтому я хочу провести явные проверки (за исключением случаев, если тип является чистым логином). Это станет: < /p>
if (something === undefined || something === null) { // Or for short `== null`
return // can be anything here, but it's often a return
}
if (something !== undefined && something !== null) { // Or for short `!= null`
// Use the variable here because we checked it is not null nor undefined
}
if (someBoolean) { // This is typed boolean so it stays the same
}
< /code>
Правило также будет применено к тройному выражению, а в других случаях. Так что, если кто-то уже сделан, я возьму его!import * as tsutils from "tsutils"
import * as ts from "typescript"
export default {
meta: {
type: "problem",
docs: {
description: "Disallow implicit falsy checks; require explicit null/undefined checks.",
recommended: true
},
schema: [],
messages: {
implicitFalsy: "Use explicit null/undefined checks instead of '!{{name}}'."
}
},
create(context) {
if (!context.parserServices?.program?.getTypeChecker) return {} // Exit if type information is unavailable
const checker = context.parserServices.program.getTypeChecker()
return {
UnaryExpression(node) {
if (node.operator === "!" && node.argument.type === "Identifier") {
const tsNode = context.parserServices.esTreeNodeToTSNodeMap.get(node.argument)
const type = checker.getTypeAtLocation(tsNode)
const isNullable = tsutils.isTypeFlagSet(type, ts.TypeFlags.Null) ||
tsutils.isTypeFlagSet(type, ts.TypeFlags.Undefined)
if (isNullable) context.report({
node,
messageId: "implicitFalsy",
data: {name: node.argument.name}
})
}
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... ull-checks
Правило Eslint, чтобы заставить явные нулевые проверки ⇐ Javascript
Форум по Javascript
-
Anonymous
1740907871
Anonymous
Я ищу правило/плагин Eslint, чтобы запретить этот вид выражения:
if (!something) {
return // can be anything here, but it's often a return
}
// Or the other way equivalent
if (something) {
// Use the variable here because we checked it is not null nor undefined
}
if (someBoolean) {
// This one is okay since it's a boolean
}
Проблема в том, что в некоторых случаях, если значение оценивается на ложный, но не неопределенный/нулевой, это не то, что мы хотели:
const something: number | undefined = 0
if (!something) {
return // Will return as 0 is falsy, but we actually wanted to check if it was undefined but forgot about this case!
}
< /code>
Поэтому я хочу провести явные проверки (за исключением случаев, если тип является чистым логином). Это станет: < /p>
if (something === undefined || something === null) { // Or for short `== null`
return // can be anything here, but it's often a return
}
if (something !== undefined && something !== null) { // Or for short `!= null`
// Use the variable here because we checked it is not null nor undefined
}
if (someBoolean) { // This is typed boolean so it stays the same
}
< /code>
Правило также будет применено к тройному выражению, а в других случаях. Так что, если кто-то уже сделан, я возьму его!import * as tsutils from "tsutils"
import * as ts from "typescript"
export default {
meta: {
type: "problem",
docs: {
description: "Disallow implicit falsy checks; require explicit null/undefined checks.",
recommended: true
},
schema: [],
messages: {
implicitFalsy: "Use explicit null/undefined checks instead of '!{{name}}'."
}
},
create(context) {
if (!context.parserServices?.program?.getTypeChecker) return {} // Exit if type information is unavailable
const checker = context.parserServices.program.getTypeChecker()
return {
UnaryExpression(node) {
if (node.operator === "!" && node.argument.type === "Identifier") {
const tsNode = context.parserServices.esTreeNodeToTSNodeMap.get(node.argument)
const type = checker.getTypeAtLocation(tsNode)
const isNullable = tsutils.isTypeFlagSet(type, ts.TypeFlags.Null) ||
tsutils.isTypeFlagSet(type, ts.TypeFlags.Undefined)
if (isNullable) context.report({
node,
messageId: "implicitFalsy",
data: {name: node.argument.name}
})
}
}
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79478859/eslint-rule-to-force-explicit-null-checks[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия