【发布时间】:2019-06-24 00:40:51
【问题描述】:
interface Company {
id: string;
name: string;
}
type input = Company;
// This fails as the types don't match
const ACME: input = { id: '123', name: 'ACME', ceo: 'Eric' };
function mapIds(ids: string[]): input[] {
// This compiles, but it shouldn't, or is Array.map returning something different?
return ids.map(id => ({ id: '1', name: '1', ceo: 'Eric' }));
// This fails as types don't match
return [{ id: '1', name: '2', ceo: 'Eric' }];
}

鉴于上述代码,typescript 编译器将不允许函数返回不属于该类型的值,但如果返回来自 Array.map,则允许。您可以在 Typescript Playground 上使用上述 sn-p 看到这一点:https://www.typescriptlang.org/play/
谁能解释一下这是怎么回事?
【问题讨论】:
标签: arrays typescript dictionary