Reputation: 5
class Student {
fullname: string;
constructor(public lastName: string, public middleName: string, public firstName: string) {
this.fullname = firstName + ", " + middleName + ", " + lastName;
}
}
interface Person {
lastName: string; middleName: string; firstName: string;
}
function greeter(person: Person) {
return "Hello, " + person.firstName + ", " + person.middleName + ", " + person.lastName;
}
let theName = new Student("first name", "Mid", "Last");
console.log(greeter(theName)) //; the result is : Hello, Last, Mid, first name what is happening?
hello, just wondering if the string order inside the classes and functions is enforced strictly or is it just bugs?
Upvotes: 0
Views: 1399
Reputation: 249506
A string
is a string
the compiler can't know what their meaning is (such as this string is a first name and this other one is a last name (well actually there is something but it's a pretty esoteric application of branded types not going to get into it here)).
You pass in the string "first name"
as the value for the lastName
parameter, and "Last"
as the value for the firstName
parameter. The result is consistent with the values you pass in. When you invoke constructors and functions the orders dictates what argument value goes in which parameter.
You can change the parameter order to a more logical order:
class Student {
constructor(public firstName: string, public middleName: string, public lastName: string) {
}
}
interface Person {
lastName: string; middleName: string; firstName: string;
}
function greeter(person: Person) {
return "Hello, " + person.firstName + ", " + person.middleName + ", " + person.lastName;
}
let theName = new Student("first name", "Mid", "Last");
console.log(greeter(theName))
Or you can take in an object literal that more explicitly states what each string means:
class Student {
lastName: string; middleName: string; firstName: string;
constructor(data: Person) {
this.lastName = data.lastName;
this.middleName = data.middleName;
this.firstName = data.firstName;
}
}
interface Person {
lastName: string; middleName: string; firstName: string;
}
function greeter(person: Person) {
return "Hello, " + person.firstName + ", " + person.middleName + ", " + person.lastName;
}
let theName = new Student({ // We state each string as a property of an object literal
firstName: "first name",
middleName: "Mid",
lastName: "Last"
});
console.log(greeter(theName))
Note I removed the fullName
field as it was not really being use anywhere (the greeter
function does not use it). You can add that as needed but I did not see a reason to include an unused field in the example.
Upvotes: 1