Khanakia
Khanakia

Reputation: 742

Why don't TypeScript throw any error when interface not properly implemented?

I have a class that implements the interface. If a class does not include the method which interface requires a typescript compiler is not throwing error but executes the error.

I want to enforce the compiler to throw an error if error is missing.

interface PersonInterface {
  name: string;  
  age: number;  
}
class Person implements PersonInterface {    
  name: string = 'Mary';  
  foo: any = 'abc';
}

alert(new Person().name)

You can check the code here at the playground https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=10&pc=31#code/JYOwLgpgTgZghgYwgAgArQM4HsQElzTxLIDeAsAFDLIhwC2EAXMhmFKAOYDc1l1cHJjQCudAEbQeySgF9KCADZwMGNJhzJgdAA4KIDcKvRRseArEQoS1XlRr0hrdiA7IAvMgDkAWThQAnp5SfMgwWFjMcCD+7l5wYghBspTyONh6AHQKWBwAFCAQAO5qJji5AJQZtAzlQA

Codesandbox LINK : https://codesandbox.io/s/typescript-3bqq4?file=/src/index.ts

Upvotes: 3

Views: 2525

Answers (1)

Youssef Egla
Youssef Egla

Reputation: 1601

The code in the playground errors out for age property and this is how you can type a method.

  • Typing a method
interface PersonInterface {
  name: string;  
  age: number;

  // type a method
  sayHello(): string

  // type function property
  repeat: (sentence: string) => string
}

class Person implements PersonInterface {    
  name: string = 'Mary';  
  foo: any = 'abc';

  sayHello() {
    return `Hello my name is ${this.name}`
  }

  repeat = (input) => {
    return `${input}`
  }
}

If you want it to error out you should consider using abstract class, One thing to note is that you can't instantiate an abstract class. Docs

abstract class PERSON {
  abstract name: string;
  abstract age: number;
  abstract repeat(sentence: string): string;
}

class Person extends PERSON{
  //
  // Will error out for not implementing
  // properties and methods
  //
}

Errors will be gone

class Person extends PERSON {
  constructor(public name: string, public age: number) {
    super();
  }

  repeat(input: string) {
    return `${input}`;
  }
}

Upvotes: 1

Related Questions