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?
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 })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.