你如何在打字稿中实现选项对象模式?

How do you implement the options object pattern in typescript?

我要在这里回答我自己的问题,因为这很难Google,我希望每个人都能更容易地找到它。

This article explains what this pattern is:

An “options object” is a programming pattern that you can use to pass any number of named arguments to a function. Rather than using an ordered list of arguments, you simply pass one argument, which is an object containing named keys for all of your options. Keep reading to learn how and why.

您可以使用打字稿功能以更简洁的方式实现此模式。具体方法见我的回答。

您可以在此处查看关于 JavaScript 的类似问题:

这个问题是不同的,因为它是关于 JavaScript 的。 JavaScript 这个问题恰好有一个答案解释了如何用打字稿的方式来做,但我发现它很难阅读,因为有太多的语法标点符号。

Here's a link to code you can play around with.

    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 "}))

这就是如何使用解构来使用选项对象模式和打字稿。这个函数让你传入一个单词数组,并用字符分隔它们。可以选择性地指定最后一个分隔符——实现“a,b,c,andd”——选择性地指定两个数组之间的分隔符——实现“a和b”或“a、b、c 和 d”,具体取决于您传入的内容——并可选择传入一个将每个单词包装在某物中的函数——以实现“'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' });