0

我知道打字稿有一个结构化的打字机制。但是,我希望,如果您有这样的课程:

class Country {
    id: string;
    name: string;
}

一个定义如下:

class ReadonlyCountry {
    readonly id: string;
    readonly name: string;     
}

如果您ReadonlyCountry在函数中返回类型为返回类型的对象,则打字系统将显示冲突Country。看起来情况并非如此,如下所示的打字稿游乐场示例。

class Country {
    id: string;
    name: string;
}

class ReadonlyCountry {
    readonly id: string;
    readonly name: string;    
}

function select(value: string): ReadonlyCountry[] {
    let country = new Country();
    country.id = "1";
    country.name = "name";
    return [country]; 
}

function select2(value: string): Country[] {
    // the type of the return here will be ReadonlyCountry[]
    // the type of the function return here is Country[]
    // why doesn't this collide?
    return select(value);
}

所以我的问题是,如何确保具有只读属性的类型和不具有只读类型且结构相同的类型在混合时显示类型错误?我是否在这里遗漏了一些愚蠢的东西,仅仅是导致这种情况发生的结构类型吗?

任何帮助,将不胜感激。

4

1 回答 1

0

是的,这是导致您的问题的结构类型。我认为你应该重新考虑你的类的结构,并尽量避免那些必须区别对待的具有相同结构的类。

作为旁注。与其创建相同类的只读版本(从而复制代码并引入维护问题),为什么不使用映射类型(参见此处),特别Readonly是已经为您预定义的类型:

function select(value: string): Readonly<Country>[]

希望这可以帮助。

于 2017-01-09T13:44:50.060 回答