Parsing error: ‘,’ expected #1716
Comments
What code were you trying to parse?
What did you expect to happen?
Don’t show any error
What actually happened?
error Parsing error: ‘,’ expected at the last 3 lines of the code.
Versions
package | version |
---|---|
@typescript-eslint/parser | 2.22.0 |
TypeScript | 3.6.3` |
ESLint | 6.8.0 |
node | 10.16.3 |
npm | 6.13.2 |
The text was updated successfully, but these errors were encountered:
This is the correct error.
Your code is invalid.
This is why you should avoid long complex lines like that.
Check the bracket matching on your last line.
@bradzacher yeah, agreed. This code is invalid. I guess my question is that this error is still showing up even when there is no rule in the ESLint config. So I am wondering which rule is looking for this type of error? Just to under how typescript-eslint is working.
ESLint parses the files you tell it to run on.
If you’re using an IDE extension, this is also true — the extension essentially just does a cli run under the hood.
Just because there are no rules, doesn’t mean there’s nothing for ESLint to check.
For example, you might have a configuration comment in one of the files that turns on a rule, which ESLint has to respect, even if there’s no rules configured in the eslintrc.
@bradzacher We don’t have any inline comment to enable ESLint rules. We also have «noInlineConfig» set to «true» in .eslintrc.json.
I looked through typescript-eslint/typescript-estree, found it choose to show a white list of errors from typescript to users as in semantic-or-syntactic-errors.ts. However I couldn’t find the specific error I see «Parsing error: ‘,’ expected» in the white list.
I am wondering if you could please help me understand where this error come from
This error comes from typescript, as we use that to parse the file.
The whitelisted you found is actually unused. In the case of a parsing error, typescript throws an error, and we do not catch it on purpose.
Note that our tooling just parses the files eslint tells us to.
You’ll have to talk to the eslint folks, or dig into the eslint codebase if you want to find out about how the parsing is coordinating.
My guess is that it still parses the file despite the fact that you have the flag set.
Источник
The error “error TS1136: Property assignment expected.” In typescript and Javascript occurs for various reason. In this ts tutorial, we will see why the error occurs and how to solve it in VSCODE. The error mainly occurs when you have an already existing babel project and you try to transition it to Typescript. The compiler will throw an error in reference to object destructuring codes like var user = {...this.props.userName};
and you might think the syntax of object destructuring in JS is different from typescript if the code previously work in babel. But the syntax is the same just that with TS you have to use an interface to define your state.
interface State {
userName: string;
}
let user: State = {userName: "John"};
// you could also add a new property and it will not throw an error like:
// “userAge” is not a known property of State
user = {...user, userAge: 20};
We have defined a state using an interface which represent the structure of how our user object is going to be like. Then we did the destructuring by assigning a value to the ‘userName’
property which already exist. And in the last line of the above code, we appended a new property to the state, but bear in mind is not part of the properties defined in the interface. So why then did we not get an error that says ‘userAge’
is not a known property of State? Well note that we did used …user to append the ‘userAge’
to whatever properties already exist in the user variable (we weren’t appending a new property to the state itself).
With the interface already defined, we can move ahead and check the properties and emit some values.
var _objectProperties = function(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var z = user.userAge;
var obj1 = objectProperties (user, ["userName"]);
Check also, Property does not exist on type ‘{}’ in TypeScript
Also, if you try to create a simple hello world application and inside the render()
method you surround the return statement with a curry-braces instead of parenthesis, you will encounter the above error. Look at below code example and how it can be solved.
import React, {Component} from "react";
class HelloWorldApplication extends Component{
render() {
// this is a bug
return {
<div className="appContainer">
<h2> Hello World </h2>
</div>
};
}
}
export default HelloWorldApplication;
There is a bug in the above code and if we run the application this is what is presented on the console.
error message:
at <div , I got “Property assignment expected.ts(1136)”
at className, I got 2 errors
Unreachable code detected.ts(7027)
‘;’ expected.ts(1005)
Check also, Typescript Tuples: Explained (With Examples)
The Solution, is to simply surround the return statement with a parenthesis instead of curry-braces as we have done below.
import React, {Component} from "react";
class HelloWorldApplication extends Component{
render() {
// Now the error is gone
return (
<div className="appContainer">
<h2> Hello World </h2>
</div>
);
}
}
export default HelloWorldApplication;
Tagged property assignment expected
Я пытаюсь создать объект внутри объекта JSON, который позже будет заполнен из FormData:
function toJSONstring(form) {
let object = {`"${form.name}": {}`}; //Property assignment expected.ts(1136)
let formData = new FormData(form);
formData.forEach((value, key) => {
// Reflect.has in favor of: object.hasOwnProperty(key)
if (!Reflect.has(object, key)) {
object[key] = value;
return;
}
if (!Array.isArray(object[key])) {
object[key] = [object[key]];
}
object[key].push(value);
});
form.reset();
return JSON.stringify(object);
}
Я хочу получить следующий JSON:
{
"network_settings": {
"connection": "wifi",
"type": "dhcp",
"ssid": "Jorj_2.4",
"ip_address": "",
"gateway": "",
"subnet": "",
"dns": ""
}
}
Но я получаю Property assignment expected.ts(1136)
.
Если я заменю
let object = {`"${form.name}": {}`};
С let object = {};
я получаю обычный объект JSON:
{
"connection": "wifi",
"type": "dhcp",
"ssid": "Jorj_2.4",
"ip_address": "",
"gateway": "",
"subnet": "",
"dns": ""
}
Как я могу создать вложенный объект, который мне нужен?
2 ответа
Лучший ответ
Вернитесь к тому, что у вас было сначала:
let object = {};
И после того, как вы заполнили объект, оберните его, используя синтаксис вычисляемого имени свойства:
return JSON.stringify({ [form.name]: object });
0
trincot
23 Сен 2021 в 18:25
Для динамических ключей в скрипте вы должны заключить свое выражение внутри []
const form = {
name: 'network_settings'
}
let obj = {[form.name]: {}};
console.log(obj);
0
Nitheesh
23 Сен 2021 в 18:32
Parsing error: ‘,’ expected #1716
Comments
What code were you trying to parse?
What did you expect to happen?
Don’t show any error
What actually happened?
error Parsing error: ‘,’ expected at the last 3 lines of the code.
Versions
package | version |
---|---|
@typescript-eslint/parser | 2.22.0 |
TypeScript | 3.6.3` |
ESLint | 6.8.0 |
node | 10.16.3 |
npm | 6.13.2 |
The text was updated successfully, but these errors were encountered:
This is the correct error.
Your code is invalid.
This is why you should avoid long complex lines like that.
Check the bracket matching on your last line.
@bradzacher yeah, agreed. This code is invalid. I guess my question is that this error is still showing up even when there is no rule in the ESLint config. So I am wondering which rule is looking for this type of error? Just to under how typescript-eslint is working.
ESLint parses the files you tell it to run on.
If you’re using an IDE extension, this is also true — the extension essentially just does a cli run under the hood.
Just because there are no rules, doesn’t mean there’s nothing for ESLint to check.
For example, you might have a configuration comment in one of the files that turns on a rule, which ESLint has to respect, even if there’s no rules configured in the eslintrc.
@bradzacher We don’t have any inline comment to enable ESLint rules. We also have «noInlineConfig» set to «true» in .eslintrc.json.
I looked through typescript-eslint/typescript-estree, found it choose to show a white list of errors from typescript to users as in semantic-or-syntactic-errors.ts. However I couldn’t find the specific error I see «Parsing error: ‘,’ expected» in the white list.
I am wondering if you could please help me understand where this error come from
This error comes from typescript, as we use that to parse the file.
The whitelisted you found is actually unused. In the case of a parsing error, typescript throws an error, and we do not catch it on purpose.
Note that our tooling just parses the files eslint tells us to.
You’ll have to talk to the eslint folks, or dig into the eslint codebase if you want to find out about how the parsing is coordinating.
My guess is that it still parses the file despite the fact that you have the flag set.
Источник
Parsing error property assignment expected
set parserOptions.ecmaFeatures.jsx: true on your test
johnboulder commented on January 13, 2023
Thank you @bradzacher that helped. Is there a guide anywhere that outlines developing rules around jsx elements specifically with typescript-eslint , I’ve struggled to find anything pointing me in the right direction.
bradzacher commented on January 13, 2023
it should be the same as developing a rule for non-jsx elements — they’re just AST like any other piece of code.
are there any particular difficulties you’re running into, specific to JSX?
johnboulder commented on January 13, 2023
If you look at the rule I shared above, I had to set // @ts-nocheck at the top because I’m getting errors with the type checking saying stuff like this:
Even though I know that property exists. idk if it’s typescript type resolution messing up or something, or what.
Additionally, the impression I’m getting from running the test against this rule is that JSXOpeningElement doesn’t ever get called, which is unexpected. I don’t see why that would be unless I’m missing some configuration somewhere else.
johnboulder commented on January 13, 2023
The results of the test after I run it:
bradzacher commented on January 13, 2023
TypeScript is correct — the issue is that you are duck-typing your nodes.
You need to refine based on the type on a node when there is a union of different nodes possible.
In this instance — JSXOpeningElement.attributes has the type (JSXAttribute | JSXSpreadAttribute)[] — i.e. your attribute variable is of type JSXAttribute | JSXSpreadAttribute . JSXSpreadAttribute does not have the property name — which is what is indicated by the error.
Here’s an example of a spread attribute:
This advice doens’t just apply to JSX nodes — it applies to the entire AST. If there is a union you must refine the type correctly using .type
Related Issues (20)
- Bug: [padding-line-between-statements] function overload should not padded with blankline
- Docs: bad links to base rules
- Enhancement: [explicit-function-return-type] add option to allow direct function calls and allowed function name regex HOT 1
- Bug: jest globals seem to be available even without env setting HOT 4
- Enhancement: [no-unused-vars] catch unused key in anonymous object type destructure HOT 1
- [member-ordering] Error for Static methods ordering HOT 6
- Base rule extension: [prefer-arrow-callback] with correct autofix HOT 3
- Rule proposal: indexed object types with infinite keyspaces must express undefined as a possible value type HOT 3
- Bug: [(2312)] An interface can only extend an object type or intersection of object types with statically known members.ts(2312) HOT 3
- Enhancement: [no-floating-promises] Ignore `Promise.allSettled` HOT 1
- Bug: Hidden (dot) directories aren’t globbed in typescript-estree’s projects glos
- Consider adoption of `exactOptionalPropertyTypes` compiler option HOT 4
- Rule proposal: Implement typescript version of eslint/no-extra-boolean-cast HOT 2
- Enhancement: [prefer-optional-chain] Also rewrite `if (x) x.something()` HOT 1
- Docs: Mention it’s ok to ping us for very old pending reviews
- ESLint incorrectly flagging variable as any HOT 4
- The JSXExpression union incorrectly includes JSXEmptyExpression HOT 1
- Rule proposal: `prefer-double-boolean-negation` [Prefer `. ` over `Boolean(. )`] HOT 8
- Bug: «utils» package is incompatible with node 18 HOT 2
- Repo: no-jest-import rule was removed HOT 1
Recommend Projects
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
TensorFlow
An Open Source Machine Learning Framework for Everyone
Django
The Web framework for perfectionists with deadlines.
Laravel
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
server
A server is a program made to process requests and deliver data to clients.
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Visualization
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
Recommend Org
We are working to build community through open source technology. NB: members must have two-factor auth.
Microsoft
Open source projects and samples from Microsoft.
Источник
Ошибки в JavaScript и как их исправить
JavaScript может быть кошмаром при отладке: некоторые ошибки, которые он выдает, могут быть очень трудны для понимания с первого взгляда, и выдаваемые номера строк также не всегда полезны. Разве не было бы полезно иметь список, глядя на который, можно понять смысл ошибок и как исправить их? Вот он!
Ниже представлен список странных ошибок в JavaScript. Разные браузеры могут выдавать разные сообщения об одинаковых ошибках, поэтому приведено несколько примеров там, где возможно.
Как читать ошибки?
Перед самим списком, давайте быстро взглянем на структуру сообщения об ошибке. Понимание структуры помогает понимать ошибки, и вы получите меньше проблем, если наткнетесь на ошибки, не представленные в этом списке.
Типичная ошибка из Chrome выглядит так:
Структура ошибки следующая:
- Uncaught TypeError: эта часть сообщения обычно не особо полезна. Uncaught значит, что ошибка не была перехвачена в catch , а TypeError — это название ошибки.
- undefined is not a function: это та самая часть про ошибку. В случае с сообщениями об ошибках, читать их нужно прямо буквально. Например, в этом случае, она значит то, что код попытался использовать значение undefined как функцию.
Другие webkit-браузеры, такие как Safari, выдают ошибки примерно в таком же формате, как и Chrome. Ошибки из Firefox похожи, но не всегда включают в себя первую часть, и последние версии Internet Explorer также выдают более простые ошибки, но в этом случае проще — не всегда значит лучше.
Теперь к самим ошибкам.
Uncaught TypeError: undefined is not a function
Связанные ошибки: number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected
Возникает при попытке вызова значения как функции, когда значение функцией не является. Например:
Эта ошибка обычно возникает, если вы пытаетесь вызвать функцию для объекта, но опечатались в названии.
Несуществующие свойства объекта по-умолчанию имеют значение undefined , что приводит к этой ошибке.
Другие вариации, такие как “number is not a function” возникают при попытке вызвать число, как будто оно является функцией.
Как исправить ошибку: убедитесь в корректности имени функции. Для этой ошибки, номер строки обычно указывает в правильное место.
Uncaught ReferenceError: Invalid left-hand side in assignment
Связанные ошибки: Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’
Вызвано попыткой присвоить значение тому, чему невозможно присвоить значение.
Наиболее частый пример этой ошибки — это условие в if:
В этом примере программист случайно использовал один знак равенства вместо двух. Выражение “left-hand side in assignment” относится к левой части знака равенства, а, как можно видеть в данном примере, левая часть содержит что-то, чему нельзя присвоить значение, что и приводит к ошибке.
Как исправить ошибку: убедитесь, что вы не пытаетесь присвоить значение результату функции или ключевому слову this .
Uncaught TypeError: Converting circular structure to JSON
Связанные ошибки: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported
Всегда вызвано циклической ссылкой в объекте, которая потом передается в JSON.stringify .
Так как a и b в примере выше имеют ссылки друг на друга, результирующий объект не может быть приведен к JSON.
Как исправить ошибку: удалите циклические ссылки, как в примере выше, из всех объектов, которые вы хотите сконвертировать в JSON.
Unexpected token ;
Связанные ошибки: Expected ), missing ) after argument list
Интерпретатор JavaScript что-то ожидал, но не обнаружил там этого. Обычно вызвано пропущенными фигурными, круглыми или квадратными скобками.
Токен в данной ошибке может быть разным — может быть написано “Unexpected token ]”, “Expected <” или что-то еще.
Как исправить ошибку: иногда номер строки не указывает на правильное местоположение, что затрудняет исправление ошибки.
Ошибка с [ ] < >( ) обычно вызвано несовпадающей парой. Проверьте, все ли ваши скобки имеют закрывающую пару. В этом случае, номер строки обычно указывает на что-то другое, а не на проблемный символ.
Unexpected / связано с регулярными выражениями. Номер строки для данного случая обычно правильный.
Unexpected; обычно вызвано символом; внутри литерала объекта или массива, или списка аргументов вызова функции. Номер строки обычно также будет верным для данного случая.
Uncaught SyntaxError: Unexpected token ILLEGAL
Связанные ошибки: Unterminated String Literal, Invalid Line Terminator
В строковом литерале пропущена закрывающая кавычка.
Как исправить ошибку: убедитесь, что все строки имеют правильные закрывающие кавычки.
Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined
Связанные ошибки: TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference
Попытка прочитать null или undefined так, как будто это объект. Например:
Как исправить ошибку: обычно вызвано опечатками. Проверьте, все ли переменные, использованные рядом со строкой, указывающей на ошибку, правильно названы.
Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined
Связанные ошибки: TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference
Попытка записать null или undefined так, как будто это объект. Например:
Как исправить ошибку: это тоже обычно вызвано ошибками. Проверьте имена переменных рядом со строкой, указывающей на ошибку.
Uncaught RangeError: Maximum call stack size exceeded
Связанные ошибки: Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow
Обычно вызвано неправильно программной логикой, что приводит к бесконечному вызову рекурсивной функции.
Как исправить ошибку: проверьте рекурсивные функции на ошибки, которые могут вынудить их делать рекурсивные вызовы вечно.
Uncaught URIError: URI malformed
Связанные ошибки: URIError: malformed URI sequence
Вызвано некорректным вызовом decodeURIComponent .
Как исправить ошибку: убедитесь, что вызовы decodeURIComponent на строке ошибки получают корректные входные данные.
XMLHttpRequest cannot load some/url. No ‘Access-Control-Allow-Origin’ header is present on the requested resource
Связанные ошибки: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at some/url
Эта проблема всегда связана с использованием XMLHttpRequest.
Как исправить ошибку: убедитесь в корректности запрашиваемого URL и в том, что он удовлетворяет same-origin policy. Хороший способ найти проблемный код — посмотреть на URL в сообщении ошибки и найти его в своём коде.
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
Связанные ошибки: InvalidStateError, DOMException code 11
Означает то, что код вызвал функцию, которую нельзя было вызывать в текущем состоянии. Обычно связано c XMLHttpRequest при попытке вызвать на нём функции до его готовности.
В данном случае вы получите ошибку потому, что функция setRequestHeader может быть вызвана только после вызова xhr.open .
Как исправить ошибку: посмотрите на код в строке, указывающей на ошибку, и убедитесь, что он вызывается в правильный момент или добавляет нужные вызовы до этого (как с xhr.open ).
Заключение
JavaScript содержит в себе одни из самых бесполезных ошибок, которые я когда-либо видел, за исключением печально известной Expected T_PAAMAYIM_NEKUDOTAYIM в PHP. Большая ознакомленность с ошибками привносит больше ясности. Современные браузеры тоже помогают, так как больше не выдают абсолютно бесполезные ошибки, как это было раньше.
Какие самые непонятные ошибки вы встречали? Делитесь своими наблюдениями в комментариях.
Источник