Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: index signature is missing in type when extending interface

Tags:

typescript

I'm trying to do an extension of one of my interfaces, but keep getting the error "index signature is missing in type {dcs: Relationship} with the following snippet:

interface Relationship {
    data: {
        id: string;
        type: string;
    }
}

interface T {
    relationships: {[key: string]: Relationship};
}

interface Test extends T {
    relationships: {
        dcs: Relationship;
    };
}

The goal is for the relationships property in T to be an object with any number of keys that are all of the Relationship type. Test is supposed to be a specific implementation of type T.

Not sure what the correct way to approach this is. Thanks in advance!

like image 740
Alexander Mattoni Avatar asked Jan 23 '16 03:01

Alexander Mattoni


People also ask

What is TypeScript index signature?

The index signature is a fitting way to handle objects with properties we know nothing about. Its syntax describes a regular property, but instead of writing a standard property name, we define the type of keys and the properties.

What is the difference between interface and type in TypeScript?

The typescript type supports only the data types and not the use of an object. The typescript interface supports the use of the object.

What is key string ]: Any in TypeScript?

The {[key: string]: any} syntax is an index signature in TypeScript and is used when we don't know all the names of a type's properties and the shape of their values ahead of time. The index signature specifies that when an object is indexed with a string, it returns a value with any type.

Is not assignable to parameter of type record string unknown?

The "Type 'unknown' is not assignable to type" error occurs when we try to assign a value with a type of unknown to a value of a different type. To solve the error, use a type assertion or a type guard to verify that the two values have compatible types before the assignment.


1 Answers

Declare Test like so:

interface Test extends T {
  relationships: {
    [key: string]: Relationship;
    dcs: Relationship;
  };
}

However, as you've noticed you end up having to declare the indexer again when you actually implement the interface. You could save some typing by doing this:

interface T {
  relationships: {
    [key: string]: Relationship;
  };
}

interface TestRelationships {
   [key: string]: Relationship;
   dcs: Relationship;
}

interface Test extends T {
  relationships: TestRelationships;
}

class T1 implements Test {
  relationships: TestRelationships;
}
like image 168
Vadim Macagon Avatar answered Oct 22 '22 15:10

Vadim Macagon