简体   繁体   English

禁止跳过未定义的可选参数

[英]Forbid skipping optional parameter with undefined

Can I (somehow?) forbid the skipping of optional parameter in typescript?我可以(以某种方式吗?)禁止跳过 typescript 中的可选参数?

class MyList {
  constructor(
    public head?: number,
    public tail?: MyList
  ){}
}

const L0 = new MyList();              // <--- empty element list - good !
const L1 = new MyList(888);           // <--- single element list - good !
const L2 = new MyList(777, L0);       // <--- general list - good !
const L3 = new MyList(undefined, L1); // <--- forbid this 

I want to statically enforce the following property on my list:我想在我的列表中静态强制执行以下属性:

  • If head is undefined then tail is also undefined (and the list is empty)如果head undefinedtailundefined (并且列表为空)

Any TypeScript trick to achieve that?任何 TypeScript 技巧可以实现吗? (This question is complementary to this question ) (这个问题是对这个问题补充

You can use something called overloading .您可以使用称为重载的东西。 This works for both methods and functions in TS.这适用于 TS 中的方法和函数。 The basic idea is that you have single function/method implementation with all the possible arguments and you can specify different combintations of the function's arguments (just like for your case where you can have 0 arguments, only the first or both).基本思想是你有单一的函数/方法实现所有可能的 arguments 并且你可以指定函数的arguments的不同组合(就像你的情况你可以有 0 arguments,只有第一个或两个)。

class MyList {
  constructor()
  constructor(head: number)
  constructor(head: number, tail: MyList)
  constructor(
    public head?: number,
    public tail?: MyList
  ){}
}

const L0 = new MyList(888);
const L1 = new MyList(777, L0);   
const L2 = new MyList(undefined, L1); // This will show error: Argument of type 'undefined' is not assignable to parameter of type 'number'.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript函数-跳过可选参数时出现命名参数问题 - JavaScript function - named parameters issue when skipping an optional parameter 将可选参数发送到 javascript function 是否有任何问题 - 测试未定义 - Is there anything wrong with sending in an OPTIONAL parameter to a javascript function - testing for undefined 如何处理 TypeScript 不将未初始化的可选参数视为未定义 - How to deal with TypeScript not treating uninitialized optional parameter as undefined 跳过 JavaScript 中的可选 function 参数 - Skipping optional function parameters in JavaScript Javascript jQuery跳过可选参数 - Javascript jQuery skipping optional params Javascript将相邻值跳过为未定义 - Javascript Skipping Adjacent Value as Undefined URL中的#之后会跳过所有参数 - # in URL skipping all parameter after that 具有可选路径参数的简单React Router提供&#39;TypeError:无法读取未定义的属性&#39;filter&#39; - Simple React Router with an Optional Path Parameter gives 'TypeError: Cannot read property 'filter' of undefined' 为什么“useParams()”返回“undefined”? 需要反应路由器/可选参数/useParams 的帮助 - Why does "useParams()" return "undefined"? Need help for react router/ optional parameter/ useParams flow可选类型参数 - flow optional type parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM