Skip to content

No IntelliSense with const assertions #41247

Closed
@cyrilletuzi

Description

@cyrilletuzi

Search Terms

const assertion

Suggestion

interface JSONSchemaString {
  type: 'string';
  enum: readonly string[];
}

interface JSONSchemaNumber {
  type: 'number';
}

type JSONSchema = JSONSchemaString | JSONSchemaNumber;

const schema: JSONSchema = {
  type: 'string';
  enum: ['hello', 'world'];
} as const;

Solutions:

  • schema should keep the exact type inferred by as const, and not be widened back to JSONSchema,
  • or there should be another way to assert as const while using a type to enable autocompletion.

Use Cases

My library (>15K weekly downloads) manages client-side storage, where data is validated at runtime via a JSON schema, so the API is basically:

this.storage.get('key', schema);
this.storage.set('key', value, schema);

Given the nature of JSON Schema structure, simplified in the example above, some cases require as const assertion to correctly infer types (for example the enum values).

When doing as below, autocompletion is available for the schema:

this.storage.get('key', { type: 'string'; enum: ['hello', 'world']; } as const);

But as the same schema must be used with .set(), a variable is required to store it, and now there will be no autocompletion at all (which is normal):

const schema = { type: 'string'; enum: ['hello', 'world']; } as const;

Unfortunately, trying to resolve this scenario by adding an explicit type adds back autocompletion, but also widen back the schema type (as if there was no as const assertion):

const schema: JSONSchema = { type: 'string'; enum: ['hello', 'world']; } as const;

So currently, I'm forced to lose autocompletion if I want to implement this feature: cyrilletuzi/angular-async-local-storage#477

Checklist

My suggestion meets these guidelines:

  • [don't know] 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

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions