函数参数的类型声明是如何工作的?

huangapple go评论68阅读模式
英文:

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 可以编译通过,原本 namestring 类型,它怎么能声明为 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 =&gt; …, 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) =&gt; … (with inferred return type) or (name: Person): … =&gt; … (explicitly typed).

Btw, you can also use the generic type parameter of map for this:

const people = [&#39;alice&#39;, &#39;bob&#39;, &#39;jan&#39;].map&lt;Person&gt;(name =&gt; ({ name }));

huangapple
  • 本文由 发表于 2023年7月11日 09:29:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76658211.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定