Skip to content

Support for as const in Javascript #35821

Closed
@arciisine

Description

@arciisine

Search Terms

const array, javascript, as const

Suggestion

The as const feature allows for treating literal arrays as tuples, and is useful for API design. I'd like to be able to leverage this from javascript when consuming a typescript package.

Seeing as the user cannot denote as const for arrays in javascript itself, I was hoping there could be a path to define a function parameter as a const array. This would only work if passing in an array literal, but for API design could be extremely powerful.

It would also be useful to convey the intent that a parameter supports a const array as well.

Use Cases

Primary use case for this, will be for API designers, to allow for more expressive typings.

Examples

Field Extraction

Typescript

function pick<T extends Readonly<string[]>, V extends Record<T[number], any>>(
     o: V, retain: T): Record<T[number], V[T[number]]> {
    ...
}

const res = pick({ a: 10, b: 20, c: 30 }, ['a'] as const);
// typeof res is { a: number }

Javascript

const res = pick({ a: 10, b: 20, c: 30 }, ['a']); // as const is not accessible
// typeof res is Record<string, any> 

CSV Object Creation

Typescript

function fromCSV<T extends Readonly<string[]>>(
   o: string[], fields: T): Record<T[number], string> {
 ...
}

const row = ['a','b','c','d'];
const obj = fromCSV(row, ['Name', 'Age', 'Height'] as const);
// typeof obj is { Name: string, Age: string, Height: string};

Javascript

const obj = fromCSV(row, ['Name', 'Age', 'Height']);
// typeof obj is Record<string, string>

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions