TypeScript:如何编写具有条件返回类型的函数 [英] TypeScript: How to write a function with conditional return type
问题描述
export type Name = { name: string }
export type Id = { id: number }
export type Value<T> = T extends string ? Name : Id
export function create<T extends string | number>(value: T): Value<T> {
if (typeof value === "string") return { name: value }
return { id: value }
}
我正在使用 TypeScript 中的条件类型.我想写一个有条件返回类型的函数.如果函数被传递一个字符串,它返回一个名称,否则返回一个 Id.
I am playing around with the conditional types in TypeScript. i would like to write a function with a conditional return type. If the function gets passed a string it returns a Name otherwise it returns an Id.
我的返回语句出现以下错误:
I get the following error on my return statements:
Type '{ name: T & string; }' is not assignable to type 'Value<T>'.
我错过了什么?谢谢!
该示例直接取自于 Build 2018 的 Anders Hejlsberg 演讲:https://youtu.be/hDACN-BGvI8?t=2241
The example taken directly from Anders Hejlsberg talk at Build 2018: https://youtu.be/hDACN-BGvI8?t=2241
他甚至说我们不必再写函数重载了……"
He even states "we do not have to write function overloads anymore..."
如果我将代码更改为仅声明,编译错误就会消失:
If I change the code to just a declaration, the compile errors go away:
export type Name = { name: string }
export type Id = { id: number }
export type Value<T> = T extends string ? Name : Id
declare function create<T extends string | number>(value: T): Value<T>
const a = create("Bob") // a : Name
const b = create(5) // b : Id
这样我们就可以声明函数签名了.我想我的问题变成了,我们将如何实际实现该功能?
So we can declare the function signature. I guess my question then becomes, how would we actually implement the function?
推荐答案
问题是函数内部 T
不知道,所以你不能真正给 Value<赋值
.一种选择是使用类型断言.更类型安全的选项是使用单独的实现签名,这样输入和输出类型会更宽松:
The problem is inside the function T
is not known, so you can't really assign a value to Value<T>
. One option would be to use a type assertion. A more type safe option would be to use a separate implementation signature, that would be more relaxed about the input and output type:
export function create<T extends string | number>(value: T): Value<T> // public signature
export function create(value: string | number): Name | Id { // more relaxed private implementation signature
if (typeof value === "string") return { name: value }
return { id: value }
}
这篇关于TypeScript:如何编写具有条件返回类型的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!