14

I am new in Typescript programming. Now I am in learning phase. I have face a problem during coding through receiving an error in back end console. The above mentioned code is:

function employee(id:number,name:string) { 
   this.id = id 
   this.name = name 
} 

var emp = new employee(123,"Smith") 
employee.prototype.email = "[email protected]" 

console.log("Employee 's Id: "+emp.id) 
console.log("Employee's name: "+emp.name) 
console.log("Employee's Email ID: "+emp.email)

Output @ Browser console is:

www.ts:10 Employee 's Id: 123
www.ts:11 Employee's name: Smith
www.ts:12 Employee's Email ID: [email protected]

And the error in Node console is:

[0] www/www.ts(6,15): error TS7009: 'new' expression, whose target lacks
a construct signature, implicitly has an 'any' type.

Please help me to resolve this error. Thanks....

2 Answers 2

14

In TypeScript you should use new only on classes. Consider rewriting it like so:

class Employee {
    id: number;
    name: string;
    email: string;

    constructor(id:number, name:string) {
        this.id = id;
        this.name = name;
    }
}

let emp = new Employee(123,"Smith");
emp.email = "[email protected]";

I don't understand what you were trying to achieve with the prototype property assignment.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you elaborate a little more?
In js it is possible and valid to use new on functions. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/….
7

If you don't want to change your existing code, you can use:

new (employee as any)(123, "smith")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.