Reputation: 6466
If I have an interface:
interface ITest {
a: number;
b: string;
}
I want to implement an interface such that a function needs to take in an object with only some defined subset of the properties of the interface, for instance for the above example, it may only need to take in a
. I've tried the following:
type WithOnly<T, K extends keyof T> = {
[K in keyof T]: T[K];
}
export const f = (x: WithOnly<ITest, 'a'>) => settings.a * 2;
But the compiler doesn't seem to like this; it wants x
to have b
also. Is there a way to implement this?
Upvotes: 1
Views: 101
Reputation: 250106
You are close, since you only want the properties specified in K
you should do [P in K]: T[P];
type WithOnly<T, K extends keyof T> = {
[P in K]: T[P];
}
Or better yet just use Pick<ITest, 'a'>
which already does what you want it to do:
interface ITest {
a: number;
b: string;
}
export const f = (x: Pick<ITest, 'a'>) => x.a * 2;
f({ a: 1 })
Upvotes: 1