类和函数内的TypeScript对象

时间:2018-08-06 12:35:29

标签: typescript

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?

你好,只是想知道类和函数中的字符串顺序是严格执行的还是仅仅是错误?

1 个答案:

答案 0 :(得分:1)

stringstring,编译器无法知道它们的含义(例如,该字符串是一个名字,而另一个则是一个姓氏(实际上,这是品牌类型的非常深奥的应用,这里就不介绍了))。

您传入字符串"first name"作为lastName参数的值,并传入"Last"作为firstName参数的值。结果与您传递的值一致。调用构造函数和函数时,命令将指示在哪个参数中使用哪个参数值。

您可以将参数顺序更改为更合理的顺序:

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)) 

或者,您也可以接受一个对象文字,该文字可以更明确地说明每个字符串的含义:

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)) 

注意,我删除了fullName字段,因为该字段实际上并未在任何地方使用(greeter函数未使用它)。您可以根据需要添加它,但我没有看到在示例中包括未使用字段的原因。