function <Obj extends object>funName(o:Obj): Obj{
...
}
Function generic as above enforces a certain relationship between params and return types, without forcing the user to actually pass a type.
Is there an equivelant object generic type (POJO - plain old JS object), without forcing the user to pass a type?
type Props = <S extends string>{
selectedTab: S
tabs: Record<S, any>
}
const props1: Props = { //ok
selectedTab: "about"
tabs: {
about: {...}
}
}
const props2: Props = { //Error
selectedTab: "contact us"
tabs: {
about: {...}
}
}
I know this could be achieved by passing a type.
const props1: Props<"about"> = {
...
}
But since automatic inference is possible for functions, perhaps it can also be used for objects.
To achieve this kind of type inference for objects, you can use a combination of type inference and helper functions to create the object. This pattern is referred to as "type inference through function context."
type Props<S extends string> = {
selectedTab: S;
tabs: Record<S, any>;
};
function createProps<S extends string>(props: Props<S>): Props<S> {
return props;
}
const props1 = createProps({
selectedTab: "about",
tabs: {
about: { content: "About content" },
},
}); // OK
const props2 = createProps({
selectedTab: "contact us",
tabs: {
about: { content: "About content" },
},
}); // Error: Type '"contact us"' is not assignable to type '"about"'.
TypeScript Playground
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