首页 > 解决方案 > 推荐在 Typescript 中使用哪个?类类型对象或具有许多参数的任何类型?

问题描述

我是 Typescript 和 Javascript 的新手。我已经编写了以下代码,它工作正常。我想了解哪个好,推荐在 Typescript 中使用。让我解释一下。当我们传递超过 4 个参数让我们说 8 个参数时,声纳会抱怨。所以我们创建一个对象并填充所有必需的字段并传递给一个函数,我们得到了结果。我们还可以定义花括号内的所有字段,如下所示。

const pType: any = {firstName: "John", lastName: "Abraham"};

同时,我们可以像这样定义一个类。

export class Person {

private _firstName: string = "";
private _lastName: string = "";

// All get set methods/functions

}

请帮助我理解上述两者之间的区别,哪个更好以及为什么在内存使用方面。为简单起见,我编写了示例类。

export class PassNReturnMultipleParams {
    
    public getAddress_Type1(person: Person): Address {
        console.log("First Name: ", person.firstName);
        // write logic to validate
        const address: Address = new Address();
        address.cityName = "Bangalore";
        address.flatName = "#123";
        address.streetName = "Richmond Road";
        
        return address;
    }
    
    public getAddress_Type2(pType: any): any {
        console.log("First Name: ", pType.firstName);
        // write logic to validate
        const adrsType: any = {cityName: "Bangalore", flatName: "#123", streetName: "Richmond Road"};
        return adrsType;
    }
    
    public check_Type1() {
        const person: Person = new Person();
        person.firstName = "John";
        // Set other values
        const adrs: Address = this.getAddress_Type1(person);
        console.log("Address City Name: ", adrs.cityName);
    }
    
    public check_Type2() {
        const pType: any = {firstName: "John", lastName: "Abraham"};
        // Set other values
        const adrs: any = this.getAddress_Type2(pType);
        console.log("Address City Name: ", adrs.cityName);
    }
    
}

const test: PassNReturnMultipleParams = new PassNReturnMultipleParams();
test.check_Type1();
test.check_Type2();

在上面的类中,有两个函数getAddress_Type1()getAddress_Type2(),在 Javascript、Typescript 世界中总是推荐使用哪一个。两者都适合我。

标签: javascriptnode.jstypescript

解决方案


在我看来,TypeScript 中不应该使用“任何”。在这种情况下,我建议您使用带有接口的普通对象:

interface PersonType {
  firstName: string;
  lastName: string;
}

const pType: PersonType = {
  firstName: "John",
  lastName: "Abraham"
};

推荐阅读