I need to specify my properties as private or public in TypeScript files (tsx
/ts
files), but unfortunately I'm getting compilation error.
It is React project using TypeScript files.
IDE is WebStorm 2021.3.
TypeScript version is 4.5.4.
I have tried to change some properties in tsconfig.json
files, but with no success.
export class Example{
private id: number;
private name: string;
constructor(id, name) {
this.id = id;
this.name = name;
}
}
This is the sample code I created just for this purpose. Other than this, I've just imported this class into app.js
file and it throws the above compilation error.
This is the TypeScript configuration:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}
CodePudding user response:
you must specified the type of the Fields
export class Exemple{
#id:number()
public name:string
}
CodePudding user response:
Am assuming you are fairly new to TS/JS - unless something is exported from a file it is private to the file.
Try to avoid classes, try to create using es6 syntax - they are much easier to work with, like so;
const exampleFunction = (param: String): string => {
return param;
}
export default exampleFunction;
Or if you must use classes.
class Point {
x: number
y: number
static instances = 0
constructor(x: number, y: number) {
this.x = x
this.y = y
}
}
Useful cheatsheet here https://devhints.io/typescript
CodePudding user response:
It seems like the tsconfig.json
you've provided was automatically generated, so that's not the cause of the issue.
Following is the valid code in typescript.
export class Example {
private id: number;
private name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
console.log(`Example ${this.id} created with name ${this.name}`);
}
}
CodePudding user response:
I solved the problem with renaming app.js
to app.tsx
.