Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Rule proposal: prefer as const #312

Closed
@mohsen1

Description

@mohsen1

In a lot of our code we have to cast string literals to literals types to conform to types so assignments work:

  type Styles = {
    position: 'relative' | 'absolute'
  }
  
  let styles = {
    position: 'relative' as 'relative'
  }
  
  let s: Styles = styles 

This is more common when using React HOCs but above example demonstrate the problem well enough.

With TypeScript 3.4 we'll have the as const literal expression which should be preferred to string or number literal types in this case because changing the value does not require changing the type.

Our example code would be better written as:

type Styles = {
  position: "relative" | "absolute";
};

let styles = {
  position: "relative" as const
};

let s: Styles = styles;

More examples:

let a: 'str' = 'str'; // bad 
let a = <'str'>'str'; // bad 
let a = 'str' as 'str' //bad 

let a = 'str' as const // good
// bad
let o = {
    foo: 'string' as 'string'
}

// good
let o = {
    foo: 'string' as const
}

Rule name

Please suggest rule name. I'm not sure how this rule should be named

Options

I can't think of any configurability for this rule

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions