TypeScript:如何根据第一个参数的值制作可选的第二个参数

编程入门 行业动态 更新时间:2024-10-27 04:27:25
本文介绍了TypeScript:如何根据第一个参数的值制作可选的第二个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

假设我有一个接受 2 个参数的函数,并且根据第一个参数的值,可能需要也可能不需要第二个参数.

Say I have a function that takes 2 args, and depending on the value of the first arg, the second arg may or may not be required.

例如:

function calculate(item: 'icon' | 'category', state: IState): void {

    if (arg1 === 'icon') {
        // code in which I don't need to access anything in state
    } 

    if (arg1 === 'category') {
        // code in which I do need to access state
    }

}

如果我按原样运行它,如果我写,我会得到一个错误

If I were to run this as is, I would get an error if I write

calculate('icon') // will cause an error

这也会引发错误,因为我没有为第二个参数传递有效值

This will also throw an error because I am not passing a valid value for the second arg

calculate('icon', null) // will also cause an error

为了不出错,我必须这样称呼它

In order to not get any errors, I have to call it like this

calculate('icon', this.state) // acceptable as long as 'this.state' meets the IState definition

如果第一个参数 = 'icon',我希望能够在不传递第二个参数的情况下调用该函数.像这样

I want to be able to call the function without passing the second argument if the first argument = 'icon'. Like this

calculate('icon') // should not cause an error

但是,如果我这样调用计算它应该会导致错误

However, if I call calculate like this it should cause an error

calculate('category') // should cause an error

任何帮助将不胜感激!

推荐答案

您可以使用多个重载:

function calculate(item: 'icon'): void
function calculate(item: 'category', state: IState): void
function calculate(item: 'icon' | 'category', state?: IState): void {

    if (item === 'icon') {
        // code in which I don't need to access anything in state
    } 

    if (item === 'category' && state) {
        // code in which I do need to access state
    }

}
calculate("icon")
calculate("category") //error

这篇关于TypeScript:如何根据第一个参数的值制作可选的第二个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-29 09:21:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1187553.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   第一个   第二个   可选   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!