打字稿类型 T 或函数 () =>T 用法 [英] Typescript type T or function () => T usage

查看:24
本文介绍了打字稿类型 T 或函数 () =>T 用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以看到在演示这个游乐场.

我创建了一个简单的泛型类型,它可以表示一个变量或一个返回变量的函数.但是,不幸的是,它不适用于典型的 typeof arg === 'function' 检查.它产生以下错误:

I've made a simple generic type which can represent either a variable or a function that returns a variable. But, unfortunately, it doesn't work with a typical typeof arg === 'function' check. It produces the following error:

此表达式不可调用.并非所有类型为 '(() => T) | 的成分(T & Function)' 是可调用的.类型 'T &函数'没有调用签名.

有没有办法不使用类型保护功能让它工作?

Is there a way to make it work without using type guard function?

type Initializer<T> = T | (() => T)

function correct(arg: Initializer<string>) {
    return typeof arg === 'function' ? arg() : arg
}

function wrong<T>(arg: Initializer<T>) {
    return typeof arg === 'function' ? arg() : arg // error here
}

const isFunction = (arg: any): arg is Function => typeof arg === 'function'

function correct_2<T>(arg: Initializer<T>) {
    return isFunction(arg) ? arg() : arg
}

推荐答案

你可以写:

type Initializer<T> = T extends any ? (T | (() => T)) : never

function correct<T>(arg: Initializer<T>): T {
    return typeof arg === 'function' ? arg() : arg // works
    // arg is Initializer<T> & Function in the true branch
}

const r1 = correct(2) // const r1: 2
const r2 = correct(() => 2) // const r2: number

在原始版本中,arg 被解析为 (() => T) |(T & Function) 在真正的分支中.TS 显然无法识别这种联合函数类型,即两个组成部分都是可调用的.至少在以上版本中,编译器很清楚您可以在函数检查后调用 arg.

In the original version, arg is resolved to (() => T) | (T & Function) in the true branch. TS apparently can't recognize for this union function type, that both constituents are callable. At least in above version, it is clear for the compiler that you can invoke arg after a function check.

可能也值得在 TypeScript 存储库中为此案例创建一个 github 问题 - 在我的意见 T &函数 应该代表某种(宽)类型的函数.

Might also be worth to create a github issue for this case in the TypeScript repository - in my opinion T & Function should represent some (wide) type of function.

这篇关于打字稿类型 T 或函数 () =>T 用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆