Prefer enum
over multiple string
constants
Wednesday, October 23, 2019
Prefer enum
over multiple string
constants
Having "magic" strings in your code can lead to issues whereas using an enumeration that is the single source of truth for the string value can harden your codebase.
Instructions
checkmark-circle
use string and integer enumerations for constant values
error-circle
using string and numeric constant values repeatedly
info-circle
enumeration values are a single source of truth
enumeration members are type-checked by the TypeScript compiler
Code Examples
use enumerations for constant values
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
enum AccessLevel {
User,
Editor,
Admin
}
interface AppProps { }
interface AppState {
user: {
displayName: string,
accessLevel: AccessLevel
};
}
class App extends Component<AppProps, AppState> {
constructor(props) {
super(props);
this.state = {
user: {
displayName: 'Brian',
accessLevel: AccessLevel.Admin
}
};
}
render() {
return (
<div>
<Hello name={this.state.user.displayName} />
{this.state.user.accessLevel === AccessLevel.Admin && <a href="/admin">admin</a>}
</div>
);
}
}
render(<App />, document.getElementById('root'));
avoid using integer constants
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
interface AppProps { }
interface AppState {
user: {
displayName: string,
accessLevel: number
};
}
class App extends Component<AppProps, AppState> {
constructor(props) {
super(props);
this.state = {
user: {
displayName: 'Brian',
accessLevel: 2
}
};
}
render() {
return (
<div>
<Hello name={this.state.user.displayName} />
{this.state.user.accessLevel > 1 && <a href="/admin">admin</a>}
</div>
);
}
}
render(<App />, document.getElementById('root'));
avoid using string constants
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
interface AppProps { }
interface AppState {
user: {
displayName: string,
accessLevel: string
};
}
class App extends Component<AppProps, AppState> {
constructor(props) {
super(props);
this.state = {
user: {
displayName: 'Brian',
accessLevel: 'admin'
}
};
}
render() {
return (
<div>
<Hello name={this.state.user.displayName} />
{this.state.user.accessLevel === 'admin' && <a href="/admin">admin</a>}
</div>
);
}
}
render(<App />, document.getElementById('root'));
Have a question or comment?