Reputation: 1701
I am a typescript starter and need to create a passport strategy. I stumbled across a line which I completely don't understand (complete code see here).
type StrategyCreated<T, O = T & StrategyCreatedStatic> = {
[P in keyof O]: O[P];
};
Can someone explain in plain English what this means?
Upvotes: 2
Views: 742
Reputation: 477
The keyof O
part is a list of all keys of an Object.
P in
declares that the value of P should be contained in a list of possible values which in your example would be the keys of O
, which is actually just a proxy for the type T & StrategyCreatedStatic
. So the line reads "[Properties contained in the keys of type O]: O[P];" "O[P]" determines the value type of the Property.
As an example:
interface Foo {
hello: string;
world: number;
}
type StrategyCreated<T, O = T & StrategyCreatedStatic> = {
[P in keyof O]: O[P];
};
const a: StrategyCreated<Foo> = { hello: "one", world: 2 }; // valid
const b: StrategyCreated<Foo> = { foo: true, bar: false }; // invalid
Upvotes: 1
Reputation: 250106
It a mapped type. You can read mode about them here. The basic idea is that it maps a given type (O
in your case) to another type.
It does this by iterating each key from O (keyof O
) in the P
type parameter ([P in keyof O]
) and assigning a new type for that key. In this case the type is the same as the original type of the P
property in O
(O[P]
).
This particular type just maps O
(which is an intersection of T
and StrategyCreatedStatic
) to a type with the same properties as the original intersection. The aim is probably to remove the intersection from the resulting type.
Upvotes: 3