Skip to content

Expressions for string-literal types #12861

Closed
@stevekane

Description

@stevekane

TypeScript Version: 2.2

Code

/*
 We need to create enumerated literal types for this domain that look like the following:
 semantic: 'POSITION_1'
 semantic: 'NORMAL_32'
 semantic: 'TEXCOORD_6'

 it would be nice to capture these string literals via type-level expressions at compile-time.
*/
// current approach
type Semantic
  = 'POSITION_0'
  | 'POSITION_1',
  // ...
  | 'NORMAL_0',
  // ...

// proposed shorthand via type-level compile-time expressions
type Semantic
  = 'POSITION_' + ( '1' | '2' | '3' | '4' )
  | 'NORMAL_' + ( '1' | '2' | '3' | '4' )

// "final-form" ?
type Semantic
  = [ ...Array(10).keys() ].map(k => 'POSITION_' + k)
  = [ ...Array(10).keys() ].map(k => 'NORMAL_' + k)

Expected behavior:
Evaluating standard ES6 during compile-time would really open up some expressiveness in defining types like these. This sort of compile-time expression evaluation is spiritually similar to the enum expressions that are available today.

Actual behavior:

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already createdSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions