简体   繁体   English

typescript generics 的默认参数

[英]Default params for typescript generics

Say I have说我有

const myFunc = <T, > (data: T) => {
  return data?.map((d) => ({name: d.name})
}

Ts throws an error saying: Property 'name' does not exist on type 'T' , which makes sense so I can fix it with Ts 抛出一条错误消息: Property 'name' does not exist on type 'T' ,这是有道理的,所以我可以修复它

const myFunc = <T extends {name: string}> (data: T) => {
  return data?.map((d) => ({name: d.name})
}

but the problem is that because I wanted T to be generic if I then call this function with但问题是,因为我希望T是通用的,如果我随后调用这个 function

myFunc(x: number)

I get an error saying the types do not match, but I want it to match the type I pass in?我收到一条错误消息,指出类型不匹配,但我希望它与我传入的类型匹配?

I should make something else clear I have a react component that has a prop called myFunc and the myFunc I've defined below is the default prop but a user could pass their own in我应该说清楚我有一个反应组件,它有一个名为myFunc的道具,我在下面定义的myFunc是默认道具,但用户可以传递自己的道具

Well by extending the type like that, the type needs to be an object that contains a name.那么通过像这样扩展类型,该类型需要是一个包含名称的 object。

So try this所以试试这个

const myFunc = <Type extends {name: string} | number> (data: Type) => {
  return data?.map((d) => ({name: d.name})
}

(T i deprecated, so using Type instead) (我已弃用,因此改用 Type)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM