首页 > 解决方案 > 打字稿通用转换函数

问题描述

我在 typescript v4.0.2 中使用泛型并遇到了这个奇怪的问题。为什么在我缩小范围后编译器会抱怨T不是?string

function foo<T>(arg: T): T {
    if (typeof arg === "string") {
        return "hello"
    }

    return arg
}

错误是:

Type 'string' is not assignable to type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'string'.

标签: typescripttypescript-generics

解决方案


这个函数签名:

foo<T>(arg: T): T

返回与其参数相同的类型。这意味着如果您传入 string "Sebastian",您希望"Sebastian"返回,而不仅仅是任何字符串。但是按照您编写此函数的方式,它会返回"hello",它具有不同的字符串文字类型。

为了支持这个逻辑,我认为函数重载是你想要的。您将为返回字符串的字符串创建一个特殊的调用签名,然后为处理所有其他参数类型的通用调用签名。

function foo(arg: string): "hello"
function foo<T>(arg: T): T
function foo<T>(arg: T): T | "hello" {
    if (typeof arg === "string") {
        return "hello"
    }

    return arg
}

const a = foo('testing')     // type: "hello"
const b = foo(123)           // type: 123
const c = foo(123 as number) // type: number
const d = foo({ abc: 123 })  // type: { abc: 123 }

操场


推荐阅读