Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement all interface members

Tags:

typescript

I have a TypeScript interface. The problem is it has about 40 members. When I use it and I implement only chosen members I get an error that there are some missing. How to ignore it? Do I have to implement them all? This issue prevents me from casting one type into another.

E.g.

interface A {
   // 40 members
}

class B implements A {
   // only 5 members implemented
}

// somewhere in the code
var myVar1: A = something;
var myVar2: B = <B> myVar1; // here an error (can't convert because B has missing some properties and methods:/)
like image 211
Nickon Avatar asked Jan 04 '13 11:01

Nickon


People also ask

Do we need to implement all interface?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. Implement every method defined by the interface.

How many interfaces can you implement?

One class can implement any number of interfaces, allowing a single class to have multiple behaviors.

What is an implementation of an interface called?

Any class that inherits a parent class, or implements an interface is a "Polymorph" of the parent class / interface.

What are the members of interface?

Interfaces can contain instance methods, properties, events, indexers, or any combination of those four member types. Interfaces may contain static constructors, fields, constants, or operators. Beginning with C# 11, interface members that aren't fields may be static abstract .


2 Answers

in typescript you can mark items as optional:

interface Person {
    name: string;
    address?: string;
}

name is required and address is optional for implementation

like image 185
Rafal Avatar answered Oct 15 '22 11:10

Rafal


If you promise that you implement an interface, you have to implement it all.

One solution would be to have a base class that implements the 40 properties if you only want to deal with 5 properties in B.

interface A {
   propA: string;
   propB: string;
}

class C implements A {
    public propA = "";
    public propB = "";
}

class B extends C {
   public propB = "Example";
}

var myVar1: A;
var myVar2: B = <B> myVar1;
like image 36
Fenton Avatar answered Oct 15 '22 09:10

Fenton