简体   繁体   English

如何定义一种类型,使其只需要实现另一个接口的一个属性

[英]How to define an type such that it only needs to implement one property of another interface

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 .我想实现一个接口,这样 function 需要接受一个 object ,其中只包含接口属性的一些定义子集,例如对于上面的例子,它可能只需要接受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.它希望x也有b 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];你很接近,因为你只想要K中指定的属性,你应该做[P in K]: T[P];


type WithOnly<T, K extends keyof T> = {
    [P in K]: T[P];
}

Play

Or better yet just use Pick<ITest, 'a'> which already does what you want it to do:或者更好的是只使用Pick<ITest, 'a'> ,它已经做了你想做的事情:

interface ITest {
    a: number;
    b: string;
}
export const f = (x: Pick<ITest, 'a'>) => x.a * 2;

f({ a: 1 })

Play

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM