【发布时间】:2018-11-11 12:18:30
【问题描述】:
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。
我的退货语句出现以下错误:
Type '{ name: T & string; }' is not assignable to type 'Value<T>'.
我错过了什么?谢谢!
编辑:直接取自 Anders Hejlsberg 在 Build 2018 上的演讲: https://youtu.be/hDACN-BGvI8?t=2241
他甚至说“我们不必再编写函数重载了……”
如果我将代码更改为声明,编译错误就会消失:
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
所以我们可以声明函数签名。我想我的问题就变成了,我们将如何实际实现该功能?
【问题讨论】:
-
重载函数或“强制转换”返回值是否仍然是最先进的技术?
标签: typescript