首页 > 其他分享 >[Typescript] Understanding TypeScript's Function Parameter Comparisons

[Typescript] Understanding TypeScript's Function Parameter Comparisons

时间:2024-08-06 15:16:54浏览次数:11  
标签:Function function TypeScript number Understanding Expect listenToEvent type even

Make those pass:

import { Equal, Expect } from "@total-typescript/helpers";

type Event = "click" | "hover" | "scroll";

type CallbackType = unknown;

const listenToEvent = (callback: CallbackType) => {};

listenToEvent(() => {});

listenToEvent((event) => {
  type tests = [Expect<Equal<typeof event, Event>>];
});

listenToEvent((event, x, y) => {
  type tests = [
    Expect<Equal<typeof event, Event>>,
    Expect<Equal<typeof x, number>>,
    Expect<Equal<typeof y, number>>,
  ];
});

listenToEvent((event, x, y, screenId) => {
  type tests = [
    Expect<Equal<typeof event, Event>>,
    Expect<Equal<typeof x, number>>,
    Expect<Equal<typeof y, number>>,
    Expect<Equal<typeof screenId, number>>,
  ];
});

 

You might be tempted to define the CallbackType as a function that either takes an Event by itself or along with x and y coordinates or screenId:

type CallbackType =
  | ((event: Event) => void)
  | ((event: Event, x: number, y: number) => void);
  | ((event: Event, x: number, y: number, screenId: number) => void);

However, with this change the first test call to listenToEvent with one parameter complains about an implicit any type:

listenToEvent((event) => { // red squiggly line under event
  type tests = [Expect<Equal<typeof event, Event>>]; // red squiggly line under Equal<>
})

// hovering over `event` shows:
Parameter 'event' implicitly has an 'any' type.

 

It turns out that because of the way TypeScript works, we can delete the first two members of the CallbackType union, keeping just the last one:

type CallbackType = (
  event: Event,
  x: number,
  y: number,
  screenId: number,
) => void;

With this change, all of the tests pass.

This might seem weird at first, but it makes sense when you consider how JavaScript works. Consider these function calls:

listenToEvent(() => {});

listenToEvent((event) => {
});

listenToEvent((event, x, y) => {
});

listenToEvent((event, x, y, screenId) => {
});

When implementing a function, it doesn't have to pay attention to everything that has been passed in. In each function call above, we pass the correct parameters, but the function does not necessarily use them. It can choose to ignore all parameters or pay attention to just the event, or the event and coordinates, or all four parameters.

This apply to callback function, not normal function

However, it cannot use a parameter that doesn't exist in its definition, as this would result in an error. This is why we needed to delete the first two members of the CallbackType union.

 

To further illustrate, let's look at another example of this concept.

Here we have an array of three numbers, and call map on it:

[1, 2, 3].map((num) => {
  console.log(num);
  return num;
});

The function passed to map only uses the num parameter, which represents the value. It ignores the index and entire array parameters that we could have passed in.

Just because a function can receive these parameters doesn't mean it has to handle them. This concept is crucial to understand when working with callbacks.

标签:Function,function,TypeScript,number,Understanding,Expect,listenToEvent,type,even
From: https://www.cnblogs.com/Answer1215/p/18345209

相关文章

  • 抽象摘要—利用抽象摘要的能力获取关键信息,以增强长文本下游任务能力:Improving Long T
    ImprovingLongTextUnderstandingwithKnowledgeDistilledFromSummarizationModel利用从摘要模型中提炼的知识提高长文本理解能力paper:https://arxiv.org/abs/2405.04955github:本文做的是一个利用抽象摘要的能力,去提升下游长文本任务的能力,具体来说就是,利用......
  • Function Calling + LangChain 拉通业务系统的技术架构
    近年来,大型语言模型(LLMs)如GPT-4的发展极大地推动了自然语言处理(NLP)领域的进步。这些模型在内容生成、语言翻译和对话系统等多个应用中展示了其强大的能力。然而,传统语言模型的局限性在于它们只能进行语言生成,无法与外部系统、API或自定义函数进行交互。本文将介绍如何通过Fu......
  • kotlin 与java 接口不兼容@FunctionalInterface
    需求:获取当前方法名为了获取当前方法名已知的有1.堆栈获取2.通过classs的enclosingMethod.name比较准确的是enclosingMethod,但是为了获取这个还需要一个内部类,于是用到了Runable,但是run方法没有返回值于是出现了神奇问题1.照Runnable抄一份:源码如下:@FunctionalInterfacepu......
  • BIOS1101 Evolutionary and Functional
    BIOS1101Evolutionaryand Functional Biology -2024GeneralCourseInformationCourseCode:  BIOS1101Year : 2024Term: Term2CourseDetails&OutcomesCourseDescriptionThis course examines the evolutionary history of life on earth fr......
  • 【TS】 TypeScript声明文件:打通JavaScript和TypeScript的桥梁
     TypeScript声明文件的讲解: TypeScript声明文件(DeclarationFile)在TypeScript项目中具有举足轻重的地位,它是连接TypeScript严格的类型系统与外部无类型或类型不明确的JavaScript代码的关键纽带。 声明文件的核心价值在于为TypeScript编译器提供必要的类型信息......
  • 【arxiv 2024】VideoGPT+: Integrating Image and Video Encoders for Enhanced Video
    【arxiv2024】VideoGPT+:IntegratingImageandVideoEncodersforEnhancedVideoUnderstanding一、前言Abstract1Introduction2RelatedWorks3Method4Dataset5ProposedBenchmark6Experiments7Conclusion8QualitativeResults9AdditionalImplementation......
  • OpenAI Function Call大模型调用单个多个agent案例
    参考:https://platform.deepseek.com/api-docs/zh-cn/function_callinghttps://blog.csdn.net/qq_31095905/article/details/139143778https://blog.csdn.net/jacbo/article/details/136278619##官方案例https://cookbook.openai.com/examples/how_to_call_functions_wi......
  • TypeScript 基础类型与类型声明
    前言在JavaScript中,变量是没有类型的,变量的值的类型是在运行时确定的,这被称为动态类型。这意味着可以在不同的时间将不同类型的值赋给同一个变量,并且JavaScript会在运行时根据当前赋给变量的值来确定其类型。示例:leta;//声明一个变量aa=10;//此时a的......
  • TypeScript 类型断言、类型推论
    类型断言类型断言是一种TypeScript特性,用于告诉编译器将一个值视为特定的类型,即使编译器本身的类型推断可能不同。类型断言并不会改变变量的实际运行时类型,而是在编译阶段告知TypeScript编译器开发者期望该表达式具有某种类型。注意:类型断言不是类型转换,因为转换通常......
  • SDN(Software-Defined Networking,软件定义网络),NFV(Network Functions Virtualization,网
    目录SDN(Software-DefinedNetworking,软件定义网络)NFV(NetworkFunctionsVirtualization,网络功能虚拟化)SDN(软件定义网络)NFV(网络功能虚拟化)SDN的优势NFV的优势DC(数据中心)网关与MEC(移动边缘计算)节点DC网关MEC节点DC网关与MEC节点的协同作用SDN(Software-DefinedNet......