English 中文(简体)
如何使参数在标注中输入但可选的参数
原标题:How to make a parameter typed but optional in typescript
  • 时间:2024-05-16 02:31:47
  •  标签:
  • typescript

我试图在我的函数中做一个参数可选性, 输入标注正丢弃一个错误 。

示例代码:

showDialog(title: string, value: string, callback: Function = null) {
       
}

标注错误 :

Type  null  is not assignable to type  Function .ts(2322)

回调是可选的。 我如何避免此错误?

问题回答

s 在 < a href=>" https://www.typescriptlang.org/docs/handbook/2/conflices.html#optional-paraters" rel=“不跟随 nofolverer” > optional 参数 和可能为 null 的参数之间有区别。

对于一个隐含输入为 T\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\可以\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

showDialog(title: string, value: string, callback?: Function) {}

可选参数必须放在参数列表的末尾,也就是说,不能随附所需的参数。

用于 null 的参数,您将使用 < a href="https://www. typescriptlan.org/docs/handbook/2/ everyday-types.html#union-types" rel=“nofollown noreferrer” > union type :

showDialog(title: string, value: string, callback: Function | null) {}

您也可以给出 null 的默认值:

showDialog(title: string, value: string, callback: Function | null=null) {}

您不需要使用 Null 来定义可选参数。 参数是可选参数, 而不是用于定义任何变量的“ ” 标注。

示例1:使用可选箭头函数。

function showDialog(title: string, value: string, callback?: ()=>{}) {
       
}

示例2:函数的返回类型

function showDialog(title: string, value: string, callback?: () => void): void {
 
}

实例3:使用功能关键字

function showDialog(title: string, value: string, callback?: Function) {

}




相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...