我知道打字稿有一个结构化的打字机制。但是,我希望,如果您有这样的课程:
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);
}
所以我的问题是,如何确保具有只读属性的类型和不具有只读类型且结构相同的类型在混合时显示类型错误?我是否在这里遗漏了一些愚蠢的东西,仅仅是导致这种情况发生的结构类型吗?
任何帮助,将不胜感激。