Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

typescript - Assessing a Function's Argument Types From Tuple

I am trying to use tuple type as function argument's type.

type T_a = (a1: string, a2: number) => boolean
const a: T_a = (a1, a2) => a1.length >= a2

type T_b_arguments = [number, string]
type T_b = (...T_b_arguments) => boolean
const b: T_b = (b1, b2) => b1 < b2.length

// Example:
b(1, 'mystring) // true

Typescript playground

How can I do this?

question from:https://stackoverflow.com/questions/65853998/assessing-a-functions-argument-types-from-tuple

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A function's formal parameters are defined as parameter_name followed by an optional type annotation. That is name or name: type annotation

If no type annotation is specified and none can be inferred, the parameter will have type any.

In the case of a rest parameter, written ...parameter, if no type annotation is specified and none can be inferred, ...parameter will have type any[].

Therefore, in the

type T_b = (...T_b_arguments) => boolean

T_b_arguments does not refer to a type but is the name of a rest parameter of type any[]

To correct this, you must name the parameter and apply the type annotation, T_b_arguments

type T_b = (...args: T_b_arguments) => boolean

Note that the ... syntax is not applied to the parameter type but to the parameter name.

Here is the fully working code

type T_a = (a1: string, a2: number) => boolean
const a: T_a = (a1, a2) => a1.length >= a2

type T_b_arguments = [number, string]
type T_b = (...args: T_b_arguments) => boolean
const b: T_b = (b1, b2) => b1 < b2.length

b(1, 'mystring') // true

Playground Link


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...