简体   繁体   English

JavaScript:切换非布尔值的简写

[英]JavaScript: Shorthand to toggle a non-boolean value

Is there a better shorthand to toggle foo ?有没有更好的简写来切换foo

type Foo = 'BAR' | 'BAZ';

let foo: Foo = 'BAR';

const toggleFoo = () => {
  foo = foo === 'BAR' ? 'BAZ' : foo;
};

toggleFoo();

You could take an object with the opposite as value.您可以取一个 object 值相反的值。

const toggleFoo = () => {
  foo = { BAR: 'BAZ', BAZ: 'BAR' }[foo];
};

With only two states, it can be simpler to use 0 to represent "off" and 1 to represent "on".只有两种状态,使用0表示“关闭”,使用1表示“开启”会更简单。 This has the added advantage of being simple to use in an if -statement.这具有在if语句中易于使用的额外优势。

let foo = 1;
const toggleFoo = () => foo ^= 1;
if(foo){
   //on
} else {
  //off
}

Here's another idea if you want a reusable way of toggling between two states.如果您想要一种在两种状态之间切换的可重用方式,这是另一个想法。

const createToggler = <F, T>(toggleStates: [F, T], initialState = false) => {
  let state = initialState
  return () => {
    state = !state
    return toggleStates[+state] // convert boolean to number for indexing
  }
}

TypeScript playground TypeScript操场

(Not sure if there's any way of avoiding a runtime typecheck of the return value, though, in case it's a non primitive such as my mixedToggler example.) (不确定是否有任何方法可以避免返回值的运行时类型检查,以防它是非原始的,例如我的mixedToggler示例。)

Merging some of the answers I came to this approach:合并我对这种方法的一些答案:

enum StateValues {
  OFF = 0,
  ON = 1
}

type State = StateValues.OFF | StateValues.ON;

const toggleState = (state: State) => {
  return state ^= 1
}

let myState: State = StateValues.OFF;

console.log(StateValues[myState]); // "OFF"

myState = toggleState(myState);
console.log(StateValues[myState]); // "ON"

myState = toggleState(myState);
console.log(StateValues[myState]); // "OFF"

TypeScript playground 打字游乐场

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

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