英文:
How does type declaration work for function parameters?
问题
下面是代码部分的翻译:
interface Person { name: string };
const people = ['alice', 'bob', 'jan'].map(name => ({ name }))
// { name: string; }[]... but we want Person[]
const people = ['alice', 'bob', 'jan'].map(name => {
   const person: Person = { name };  // 额外的代码,需要更好的方法
   return person
});   // 类型是 Person[]
所以它也可以这样写:
const people = ['alice', 'bob', 'jan'].map(
   (name): Person => ({ name })
); // 类型是 Person[]
我不明白为什么 (name): Person 可以编译通过,原本 name 是 string 类型,它怎么能声明为 Person 类型呢?显然你不能这样做:
let p: Person = "Alice";  // 编译错误,类型 'string' 不能分配给类型 'Person'
英文:
below is the code:
interface Person { name: string };
const people = ['alice', 'bob', 'jan'].map(name => ({name}))   
// { name: string; }[]... but we want Person[]
const people = ['alice', 'bob', 'jan'].map(name => {
   const person: Person = {name};  // extra noise, need a better approach
   return person
});   // type is Person[]
so it can also be written as:
const people = ['alice', 'bob', 'jan'].map(
   (name): Person => ({ name })
); // Type is Person[]
I don't understand why (name): Person can be compiled, isn't that name is originally string type, how can it be declared to Person type? obviously you can't do:
let p: Person = "Alice";  // compile error, Type 'string' is not assignable to type 'Person'
答案1
得分: 3
只返回翻译好的部分:
这是 (name): Person => …,其中 Person 指定了箭头函数的返回类型。 它不声明参数的类型,它将是 (name: Person) => …(带有推断返回类型)或者 (name: Person): … => …(显式类型声明)。
顺便说一下,你也可以使用 map 的泛型类型参数来实现这个:
const people = ['alice', 'bob', 'jan'].map<Person>(name => ({ name }));
英文:
It's (name): Person => …, where Person specifies the return type of the arrow function. It does not declare the type of the parameter, which would have been (name: Person) => … (with inferred return type) or (name: Person): … => … (explicitly typed).
Btw, you can also use the generic type parameter of map for this:
const people = ['alice', 'bob', 'jan'].map<Person>(name => ({ name }));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论