繁体   English   中英

如何在 typescript 中实现选项 object 模式?

[英]How do you implement the options object pattern in typescript?

我将在这里回答我自己的问题,因为这对谷歌来说非常困难,我希望每个人都更容易找到它。

本文解释了这种模式是什么:

“选项对象”是一种编程模式,可用于将任意数量的命名 arguments 传递给 function。 无需使用 arguments 的有序列表,您只需传递一个参数,即 object,其中包含所有选项的命名键。 继续阅读以了解如何以及为什么。

您可以使用 typescript 功能以更简洁的方式实现此模式。 如何查看我的答案。

您可以在这里看到关于 JavaScript 的类似问题: Implement JavaScript options object parameter pattern?

这个问题是不同的,因为它是关于 JavaScript。 碰巧有一个关于 JavaScript 问题的答案,它解释了如何以 typescript 方式进行操作,但我发现很难阅读,因为语法标点符号太多。

这是您可以使用的代码的链接。

    interface Options {
      lastSeparator?: string;
      separatorBetweenArrayOfTwo?: string;
      wrap?: (word: string) => string;
    }
    
    const separatedMessage = (
      words: string[],
      separator: string,
      { 
        lastSeparator = separator, 
        separatorBetweenArrayOfTwo = lastSeparator, 
        wrap = (word: string): string => {
          return word.toString();
        }
       }: Options = {} // the = {} at the end means you don't have to pass in an Object here if you don't want.
    ): string => {
      let buf = '';
    
      words.forEach((word, index, array) => {
        if (index !== 0) {
          if (array.length === 2) {
            buf += separatorBetweenArrayOfTwo;
          } else if (index === array.length - 1) {
            buf += lastSeparator;
          } else {
            buf += separator;
          }
        }
          buf += wrap(word);    
      });
      return buf;
    };
    
    console.log(separatedMessage(["a", "b", "c", "d"], ", "))
    console.log(separatedMessage(["a", "b"], ", ", {}))
    console.log(separatedMessage(["a", "b"], ", ", {lastSeparator: ", and "}))
    console.log(separatedMessage(["a", "b"], ", ", {lastSeparator: ", and ", separatorBetweenArrayOfTwo: " and "}))

这就是如何使用解构,您可以使用选项 object 模式和 typescript。 这个 function 允许您传入一个单词数组,并用字符分隔它们。 您可以选择指定最后一个分隔符——实现“a、b、cd”——可选地指定arrays之间的分隔符——实现“a和b”或“a、b、Z4A8A08F09D37B73B5F33和d” " 取决于您传入的内容 - 并可选择传入一个 function 将每个单词包装在某物中 - 以实现“'a'、'b'、'c' 和 'd'”。

我们可以为接口定义特定的键值对或任何键值对,然后销毁这些值。

 interface Person { name: string; age: number; gender: string; hobby?: string; [key: string]: any; } function logPerson(person: Person) { console.log(person); return person; } function logPerson1(person: { [key: string]: any }) { console.log(person); } console.clear(); logPerson({ name: 'Kevin', age: 33, gender: 'male', hobby: 'basketball', hah: 'Hah' }); logPerson1({ name: 'Lucy', age: 100, gender: 'female', extra: 'extra property' });

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM