'Incompatible type interfaces when one should be a subset of another
I have an interface called CreateForumValues, which is essentially a more specific interface than one called Values.
I have a function (here called test(values)) that takes in it an object of interface Values:
export interface Values {
[name: string]: string;
}
export interface CreateForumValues {
siteUrl: string;
name: string;
shortName: string;
}
export const createForumDefaults: CreateForumValues = {
siteUrl: "",
name: "",
shortName: "",
};
function Test({ values }: { values: Values }) {
// do something with values
}
Test({ values: createForumDefaults });
I would expect that since CreateForumValues is a more specific, and basically subset of Values, that it would be passable with TypeScript, but I am getting this error:
Type 'CreateForumValues' is not assignable to type 'Values'.
Index signature for type 'string' is missing in type 'CreateForumValues'.ts(2322)
which doesn't make a lot of sense because each of the indexes are essentially strings.
What needs to be done to make these two compatible with each other?
Also, this will be in react, and Test would really be called in JSX like so:
<Test values={createForumDefaults}/>
and there will be different collections of values passed into Test that will be similar to CreateForumValues, but with different property sets.
Solution 1:[1]
You'll need to add [name: string]: string to your CreateForumValues or have CreateForumValues extend Values.
Despite the fact that all values you've defined are strings, other definitions might extend from yours and define incompatible other values like this:
interface CreateExtendedForumValues extends CreateForumValues {
notAString: SomeComplexObjectType;
}
You could also define Values to have string keys and unknown type, but at that point Values might not provide very much value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeff Bowman |
