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!
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.
The typescript type supports only the data types and not the use of an object. The typescript interface supports the use of the object.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With