Pyt*_*ner 5 javascript node.js typescript
我是 Typescript 和 Javascript 新手。我编写了以下代码,效果很好。我想了解哪个好并建议在 Typescript 中使用。让我解释一下。当我们传递超过 4 个参数(比如 8 个参数)时,声纳会抱怨。因此,我们创建一个对象并填充所有必需的字段并传递给函数,然后我们得到结果。我们还可以定义大括号内的所有字段,如下所示。
const pType: any = {firstName: "John", lastName: "Abraham"};
Run Code Online (Sandbox Code Playgroud)
同时我们可以定义一个这样的类。
export class Person {
private _firstName: string = "";
private _lastName: string = "";
// All get set methods/functions
}
Run Code Online (Sandbox Code Playgroud)
请帮助我理解上述两者之间的区别,哪个更好以及为什么在内存使用方面更好。为了简单起见,我编写了示例类。
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();
Run Code Online (Sandbox Code Playgroud)
在上面的类中,有两个函数getAddress_Type1()和getAddress_Type2(),在 Javascript、Typescript 世界中总是推荐使用其中一个。两者都适合我。
小智 3
我认为,TypeScript 中不应该使用“any”。在这种情况下,我建议您使用带有接口的普通对象:
interface PersonType {
firstName: string;
lastName: string;
}
const pType: PersonType = {
firstName: "John",
lastName: "Abraham"
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
345 次 |
| 最近记录: |