简体   繁体   中英

Literal values for tuple parameters in 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] ]

How can I achieve this?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM