When working with the specified types below
interface Base {
id: string;
}
interface A extends Base {
propA: string;
}
interface B extends Base {
propB: string;
}
I am looking to create a unique MyGeneric<T>
with specific constraints:
T
must be an objectT
keys should be of typestring
T
values must be of typeinstanceOf Base
(either directly of typeBase
, or extending Base)(The third requirement has been rephrased for clarity and better understanding)
In my initial attempt, I created
interface MyConstraint {
[key: string]: Base
}
interface MyGeneric<T extends MyConstraint> {
data: T
}
However, this approach presents two drawbacks when used by the user:
interface userDefinedInterface1 {
a: A;
b: B;
}
function foo1(p: MyGeneric<userDefinedInterface1>):void {
//drawback 1: encountering TS2344 error:
//Type 'userDefinedInterface1' does not satisfy the constraint 'userDefinedInterface1'. //Index signature is missing in type 'userDefinedInterface1'.
}
//To address drawback 1, the user must extend MyConstraint
interface userDefinedInterface2 extends MyConstraint {
a: A;
b: B;
}
function foo2(p: MyGeneric<userDefinedInterface2>):void {
//drawback 2: all string properties are considered valid due to [key: string]
console.log(p.data.arbitraryKey);//this is considered valid
}
Can we define interface MyGeneric<T>
in a way that meets the three aforementioned constraints without these two issues?