将对象传递给一个函数,并使用该对象的键/值来调用另一个函数

时间:2018-04-27 01:03:32

标签: typescript

在python中我通常只做这样的事情:

## single person
class Person:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

## empty when instantiated
class People:
    def __init_(self):
        self._people = {}

    def update(self, Person):
        self._people[Person.first_name] = Person

    def update2(self, person):
        self.update(Person(**person))


people = People()
people.update2({'first_name': 'Mike', 'last_name': 'Smith', 'age':7})

我的目标是在打字稿中实现这种确切的行为。这是我到目前为止所拥有的。

class  Person {
    constructor(first_name, last_name, age){}
}

class People{
    public _people;

    constructor(){
        //not sure if there is a cleaner way to add _people to new instances
        this._people = {}
    }

    update(Person){
        this._people[Person.first_name] = Person
    }
    update2(my_object){
        //Person(my_object) should return an instance of the Person class
        this.update(Person(my_object))
    }
}

var people = new People()
people.update2({first_name:'Bob', last_name:'Smith', age:7})

非蟒蛇人的解释。

目标是创建一个可以保存Person类实例的People类。我想将一个对象传递给update2,并使用该对象的键/值来创建Person类的实例。

如果有什么不清楚,请告诉我。

1 个答案:

答案 0 :(得分:1)

以下是我将如何在TypeScript中编写它。我已经改变了一些变量的情况,使其更像“TypeScript-like'。

我还添加了他们失踪的类型。

class Person {
    // Public getters/setters
    public firstName: string;
    public lastName: string;
    public age: number;

    constructor({firstName, lastName, age}: { firstName?: string, lastName?: string, age?: number }) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
}

class People {
    // Declare _people as an object with keys as strings and values as Person instances
    public _people: {[key: string]: Person};

    update(person: Person) {
        this._people[person.firstName] = person;
    }

    // Add a signature to obj to make it clear what you are expecting
    update2(obj: {firstName: string, lastName: string, age: number}) {
        this.update(new Person(obj));
    }
}

var people = new People()
people.update2({ firstName: 'Bob', lastName: 'Smith', age: 7 });

console.log(people._people);

或者,如果Person是一个简单的数据对象,我建议您不要使用class,而应使用带有接口的简单JS对象:

interface Person {
    firstName?: string,
    lastName?: string,
    age?: number
}

const person1: Person = { firstName: 'Jane', lastName: 'Doe', age: 25};