简体   繁体   English

定义返回类型与其第一个参数相同的函数的正确方法是什么

[英]what's the correct way to define a function with returned type the same as its first parameter

What I want is simple, I want a function return a type the same as its parameter.我想要的很简单,我想要一个函数返回与其参数相同的类型。 I've tried the below code but it's wrong.我试过下面的代码,但它是错误的。

type IF = <T>(name: T) => T

let f: IF = (name: string) => {
    return name + ''
}

However, below code works but it's not my wanted但是,下面的代码有效,但这不是我想要的

type IF = <T>(name: T) => T

let f: IF = (name) => {
    return name
}

Looks like you've misplaced <T> The code below works看起来你放错了<T>下面的代码有效

type IF<T> = (name: T) => T

let f: IF<string> = (name: string) => {
    return name + ''
}

暂无
暂无

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

相关问题 使用返回与其参数相同类型的可区分联合来声明 TypeScript 函数的最佳方法是什么? - What's the best way to declare a TypeScript function with a discriminated union that returns the same type as its parameter? 根据 function 的第一个参数定义第二个参数的类型为通用 class - define type of second parameter as generic class according to the first parameter of function 在 TypeScript 中使用一个参数来定义同一个函数中另一个参数的类型 - Using a parameter to define the type of another parameter in the same function in TypeScript 根据 TypeScript 中的参数在字典中定义 function 的返回类型 - Define return type of a function in dictionary based on its parameter in TypeScript 在TypeScript中定义React组件的contextTypes的正确方法是什么? - What is the correct way to define a React component's contextTypes in TypeScript? 在 TypeScript 中键入此函数的正确方法是什么? - What is the correct way to type this function in TypeScript? 高阶函数的返回函数参数的缩小类型 - Narrow down type of the returned function's parameter of a high order function 这个 TypeScript 函数的正确返回类型是什么? - What's the correct return type for this TypeScript function? Typescript 函数定义以确保第二个参数与第一个参数的类型相同 - Typescript function definition to ensure second parameter is same type as first parameter 设置作为参数传递的元素类型的正确方法是什么 - What is the correct way to set an element type passed as a parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM