0

Why when I try to define object method:

export class Helper {
    function add(x: number, y: number): number {
        return x + y;
    }
}

I get following error:

Unexpected token. A constructor, method, accessor, or property was expected.

I followed example from this site: https://www.typescriptlang.org/docs/handbook/functions.html But when I remove function keyword it works, but that contradicts the official source.

1 Answer 1

3

You should not use function inside a class! Change to it:

export class Helper {
    add(x: number, y: number): number {
        return x + y;
    }
}

Typescript doesn't allow functions as members of a class. So, change it to a method!

As said by mattjes, you could make the method static too...

export class Helper {
    static add(x: number, y: number): number {
        return x + y;
    }
}

Helper.add(1,2)
Sign up to request clarification or add additional context in comments.

2 Comments

if you want it static just put static in front of the method declaration
No I don't want static(class) method,I want non-static(object) method.

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.