Closed as not planned
Closed as not planned
Description
Given the following two types.
type Channel = {
[key: string]: number;
};
type T<C extends Channel> = {
channel: C;
props: (keyof C)[];
};
The following function is able to correctly constrain the type of the second parameter given the following function declaration and call.
function createObject<C extends Channel>(channel: C, props: (keyof C)[]): T<C> {
return {
channel,
props,
};
}
const someObject = createObject(
{
Stuff: 1,
Yarn: 2,
},
['Stuff', 'Yarn', 'Thing'] // If you try to add a string that is not a key of 'channel', you'll get a type error. Thing is inferred invalid, and I don't have to specify a generic property
);
However, this constraint is not preserved in the Parameters
utility type.
let thing: Parameters<typeof createObject> = [
{
"Stuff": 1,
"Yarn": 2,
},
["Yarn", "Stuff", "Thing"] // So... that constraint wasn't preserved.
]
At least not until the generic is explicitly set.
let thingAgain: Parameters<typeof createObject<{"Stuff":number;"Yarn":number}>> = [
{
"Stuff": 1,
"Yarn": 2,
},
["Yarn", "Stuff", "Thing"] // And we're back!
]
Ultimately, the desired functionality is to have types obtain the same type inference as functions without a runtime requirement to keep the typing/code dry.
Metadata
Metadata
Assignees
Labels
No labels