javascript - 推荐在 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 世界中总是推荐使用哪一个。两者都适合我。
解决方案
在我看来,TypeScript 中不应该使用“任何”。在这种情况下,我建议您使用带有接口的普通对象:
interface PersonType {
firstName: string;
lastName: string;
}
const pType: PersonType = {
firstName: "John",
lastName: "Abraham"
};
推荐阅读
- sql - 带有日期转换的 SQL 标量函数?
- javascript - 如何在 Sequelize 模型中使用多个 DB 连接?
- pyspark - Pyspark 数据框未正确分组
- php - 在 Session PHP 中保存复选框
- azure-ad-b2c - 将 B2C OWIN 服务从“login.microsoft.com”迁移到“b2clogin.com”
- c++ - GetVersionEx Windows 10 被检测为 Windows 8
- java - 如何用数据库数据java和hibernate填充组合框
- sql - 如何根据日期和其他字段提取交易数据中的重复项
- tomcat - 验证查询(选择 1)24/7 运行而未指定?
- c++ - C++ Qt5 QDir 重命名返回 false