首页 > 解决方案 > Mixed let/const array destructuring from split string

问题描述

TS throws an error:

'parsedHours' is never reassigned. Use 'const' instead    prefer-const
'parsedMinutes' is never reassigned. Use 'const' instead  prefer-const

When trying to deconstruct this array, after a string split:

let [
  parsedHours = '00',
  parsedMinutes = '00',
  parsedSeconds = '00',
  parsedMillis = '000'
] = "12:34:56".split(':');

if (parsedSeconds.includes('.')) {
  [parsedSeconds, parsedMillis] = parsedSeconds.split('.');
}

Hours and minutes should be declared as constants, but Seconds and Millis may change, thus should be declared as let. This can be fixed in many approaches, but I can't find a beautiful way of doing this.

Any ideas?

标签: javascriptarraystypescriptecmascript-6

解决方案


You basically have a couple of options:

  1. Turn off the lint rule (I'm 99% sure it's not TypeScript itself saying this, but TSLint or ESLint or similar).

  2. Save the array, then use const or let as desired.

  3. Use const for all of them by using a regular expression (perhaps with named capture groups) that handles the possible formats you're feeding it.

Here's #2:

const result = "12:34:56".split(":");
const [parsedHours = "00", parsedMinutes = "00"] = result;
let [, , parsedSeconds = "00", parsedMillis = "000"] = result;
// ...

Here's #3:

const rexTime = /^(?<hours>\d{1,2}):(?<minutes>\d{1,2}):(?<seconds>\d{1,2})(?:\.(?<millis>\d{1,3}))?$/;
function example(timeString) {
    const {
        groups: {
            hours = "00",
            minutes = "00",
            seconds = "00",
            millis = "000"
        } = {}
    } = rexTime.exec(timeString) ?? {};
    console.log(
        timeString,
        "=>",
        hours,
        minutes,
        seconds,
        millis
    );
}

example("12:34:56");
example("12:34:56.123");

There are a dozen different ways to spin that, that's just one of them, but it gives you the idea.


推荐阅读