bag*_*man 5 arrays dictionary typescript
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' }];
}
?
Run Code Online (Sandbox Code Playgroud)
Given the above code, the typescript compiler will not allow the function to return values that don't belong in the type, however if the return is from an Array.map, it does. You can see this with the above snippet on the Typescript Playground: https://www.typescriptlang.org/play/
Could anyone explain what's up with that?
您的映射函数没有指定返回类型,因此它可以返回任何内容。如果你想要更严格的检查,你需要明确:
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[] {
return ids.map((id):Company => ({ id: '1', name: '1', ceo: 'Eric' }));
// This fails as types don't match
return [{ id: '1', name: '2', ceo: 'Eric' }];
}
Run Code Online (Sandbox Code Playgroud)
原因是该.map函数是一个映射操作,旨在将数组中的每个元素转换为新类型。如果您不指定,TypeScript 不知道新类型是什么。
扩展下面的评论。TSC 反对线条return [{ id: '1', name: '2', ceo: 'Eric' }];,因为它期望的类型input[]并非如此。然而ids.map(id => ({ id: '1', name: '1', ceo: 'Eric' }));,它本身就很好(因为 .map 可以返回任何类型),然后将其分配给input[]允许的类型。
感谢@TitianCernicova-Dragomir 和@pswg 对此的评论。
| 归档时间: |
|
| 查看次数: |
724 次 |
| 最近记录: |