首页 > 解决方案 > 有没有更好的方法来制作 setter 非原始用户定义类型属性?

问题描述

嗨,我是打字稿的新手。我在以下示例中总结了我的用例。

class Movie {
    private crew: Crew;
    private cast: Cast;
    private locations: Location;
    private movieId;

    constructor(public id: string) {
        this.movieId = id;
    }
    public getMovieId() {
        return this.moveId;
    }
    public setCrew(value: Crew){
        this.crew = value;
    }
    public getCrew() {
        return this.crew;
    }
    ...
    //other getter and setters.
};

type Crew = {
    crew_varA: string,
    crew_varB: boolean,
    crew_varC: string,
    crew_varD: boolean,
}

type Cast = {
    cast_varE: string,
    cast_varF: string,
    cast_varG: string,
}
type Location = {
    loc_varX: string,
    loc_varY: string,
    loc_varZ: string,
}

当我创建一个 Movie 对象时,我需要调用 setCrew() 方法。但到那时,只有“crew_varA”变量才有价值。我无法仅使用一个变量调用 setCrew() 方法。我需要用一些不合适的默认值初始化所有变量。

let mv = new Movie("SpiderMan");
mv.setCrew({crew_varA: "Peter Parker", crew_varB:false, crew_varC:null, crew_varD:null}; //is there a way to set only one property of Crew and add other properties one by one based on some logic??

我不确定我的方法是否正确。我感谢您的帮助。

标签: typescript2.0

解决方案


推荐阅读