Typescript中元组参数的文字值 [英] Literal values for tuple parameters in Typescript

查看:83
本文介绍了Typescript中元组参数的文字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我知道我可以根据函数的输入值将泛型分配给元组类型

I'm aware that I can assign a generic to a tuple type based on the input value of a function, for example

declare function example<A extends [any,...any[]]>(a: A) : A
example([1,2,3,[4]]) // : [ number, number, number, number[] ]

但是我想要这样的字面值

However I'd like the literal values, like so

example([1,2,3,[4]]) // : [ 1, 2, 3, [4] ]

我该如何实现?

推荐答案

这是不可能的.选择类型以实例化类型变量时,Typescript必须为A选择单个类型.您想要的是一次实例化具有四种不同类型的A.

This is not possible. When picking a type to instantiate a type variable, Typescript has to choose a single type for A. What you want is to instantiate A with four different types at once.

这篇关于Typescript中元组参数的文字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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