12

How to implement a method in an interface in TypeScript?

interface Bar
{
    num: number;
    str: string;
    fun?(): void;
}
class Bar
{
    fun?()
    {
        console.log(this.num, this.str);
    }
}
let foo: Bar = {num: 2, str: "B"};
foo.fun();

Expected: 2 B

Actual:

Error Cannot invoke an object which is possibly 'undefined'.ts(2722)

If the optional flag is omitted from the method fun(), then the error will be:

Property 'fun' is missing in type '{ num: number; str: string; }' but required in type 'Bar'.ts(2741)

Update 1

This is a work-around that results in what is expected, though it does not seem like the proper way to do this.

if(foo.fun)
{
    foo.fun();
}

2 Answers 2

15

Implement the interface in the class you are creating and then invoke.

interface BarInterface
{
    num: number;
    str: string;
    fun: () => void;
}

class Bar implements BarInterface {
    num: number;
    str: string;

    constructor(num: number, str: string) {
        this.num = num;
        this.str = str;
    }
    fun() {
        console.log(this.num, this.str);
    }
}

let foo = new Bar(2, "B");

foo.fun();
Sign up to request clarification or add additional context in comments.

Comments

2

Typescript tells you that it is undefined because you did not provide a method to invoke in this line:

let foo: Bar = {num: 2, str: "B"};

Try

const myTestFun = () => {
  console.log('I am here!')
}
let foo: Bar = {num: 2, str: "B", fun: myTestFun };

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.