How to define properties in TypeScript class through the database?

This is my Error when I define properties in my employee.ts

click

export class Employee {
    id:number;
    fname: string;
    lastName:string;
    emailId: string; }

& I got this kind of errors

  • Property ‘id’ has no initializer and is not definitely assigned in the constructor.

  • Property ‘fname’ has no initializer and is not definitely assigned in the constructor.

  • Property ‘lastName’ has no initializer and is not definitely assigned in the constructor.

  • Property ’emailId’ has no initializer and is not definitely assigned in the constructor.

And this is my database also click

mysql> SELECT *
    -> FROM employees;
+----+-----------------+------------+-----------+
| id | email_id        | first_name | last_name |
+----+-----------------+------------+-----------+
|  1 | mara@gmail.com  | Amara      | Perera    |
|  2 | sadun@gmail.com | Sadun      | Fernando  |
+----+-----------------+------------+-----------+
2 rows in set (0.01 sec)

Here is mY Employee.java file created on eclips IDE

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employees")
public class Employee {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    
    @Column(name = "first_name")//column annotation to provide columns
    private String firstName;
    
    @Column(name = "last_name")
    private String lastName;
    
    @Column(name = "email_id")
    private String emailId;
    
    public Employee() {
        
    }
    
    //generate constructor
    public Employee(String firstName, String lastName, String emailId) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.emailId = emailId;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmailId() {
        return emailId;
    }
    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }
    
    
    

}

Can Enyone help me to solve this Error??

Answer

TypeScript is trying to warn you of a scenario like this:

const employee = new Employee();

because all properties in employee will be undefined at this point, but you defined them as numbers and strings. You can make the properties optional, initialise them in the constructor or add the following to tsconfig.json:

"strictPropertyInitialization": false

In Java you don’t have this type of check.