I am looking to define a versatile TypeScript interface that can accommodate any type, interface, or object while imposing restrictions on the types of values it contains.
Let me introduce MyInterface
, which includes properties fooIProp
and barIProp
storing strings with an example:
interface MyInterface {
fooIProp: string;
barIProp: string;
};
const testInterface: MyInterface = {
fooIProp: "foo",
barIProp: "bar"
};
Next is the MyType
type alias, featuring properties fooTProp
and barTProp
holding strings as shown here:
type MyType = {
fooTProp: string;
barTProp: string;
}
const testType: MyType = {
fooTProp: "foo",
barTProp: "bar"
}
Here's an object with properties fooObjectKey
and barObjectKey
keeping strings:
const testObject = {
fooObjectKey: "foo",
barObjectKey: "bar"
}
I have devised MyGenericInterface
that accepts objects containing only strings for keys and values:
interface MyGenericInterface { [key: string]: string }
When trying to assign testInterface
to MyGenericInterface
,
const testFromInterface: MyGenericInterface = testInterface;
const testFromType: MyGenericInterface = testType;
const testFromObject: MyGenericInterface = testObject;
A TS2322 error is thrown:
Type 'MyInterface' is not assignable to type 'MyGenericInterface'.
Index signature is missing in type 'MyInterface'.(2322)
Visit the TypeScript Playground for more insights.
Question: How can I develop a generic TypeScript interface that supports various types/interfaces/objects while controlling the types of values within?