简体   繁体   English

仅在部分课程中声明变量

[英]Declare variable only with part of class

Let's say we have a class like: 假设我们有一个类似的类:

class House {
    street: string;
    pools: number;
    helicopterLandingPlace: boolean;
}

Now i build a service to update my house. 现在,我建立了一个服务来更新我的房子。

putHouse(house: House) {
    // some put request
}

But sometime I expect just parts of the house to get updated. 但是有时候我希望房子的一部分会得到更新。

patchHouse(house: ?????) {
    // some patch request...
}

What is the cleanest way to declare the variable house with in the second function. 在第二个函数中使用变量房子声明的最干净方法是什么?

Thanks in advance for your help! 在此先感谢您的帮助!

One way to accomplish this would be by using the Partial type, something like: 实现此目的的一种方法是使用Partial类型,例如:

 class House { street: string; pools: number; helicopterLandingPlace: boolean; } function patchHouse(house: Partial<House>) { console.log(house); } patchHouse({street: 'street'}); 

Under the hood 引擎盖下

Partial<T> is an interface that has the following definition: Partial<T>是具有以下定义的接口:

type Partial<T> = { [P in keyof T]?: T[P]; };

Which means that by using the keyof operator we get something like: 这意味着通过使用keyof运算符,我们将得到如下内容:

Partial<House> {
  street: string?;
  pools: number?;
  helicpterLandingPlace: boolean?;
}

Interface segregation : 接口隔离

interface Addressable {
    street: string;
}

interface Swimmable {
    pools: number;
}

interface Landable {
    helicopterLandingPlaces: boolean;
}

class House implements Addressable, Swimmable, Landable {
    street: string;
    pools: number;
    helicopterLandingPlaces: boolean;
}

function patch(house: Swimmable) {
    house.pools++;
}

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

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