Skip to content

Support readonly types with inference #32812

Description

@orta

Search Terms

readonly without type

Suggestion

Today, in order to use a readonly type with inference you need to know typeof exists

const user = {
  name: "orta"
}

const readonlyUsers: readonly typeof user[] = [user] 

It would be nice to support shorthand syntax for this:

const user = {
  name: "orta"
}

const readonlyUsers: readonly = [user] 

Where the lack of a definition outside of readonly implies you want to keep the inferred type.

Use Cases

Making it cheaper syntactically to use readonly more often without using slightly more esoteric typescript features.

Could be negated by these though:

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.

Activity

  1. RyanCavanaugh commented on Aug 12, 2019

    @RyanCavanaugh
    Member

    Can you compare and contrast with how as const doesn't address this use case?

  2. jack-williams commented on Aug 13, 2019

    @jack-williams
    Collaborator

    From the PR that added readonly (#29435) there was a question about the behaviour of types called readonly here. The following used to compile, but does not currently:

    type readonly = string;
    const q: readonly = 'hello';

    I think there was a plan to fix this, but maybe though would need to be reviewed in light of this proposal.

  3. orta commented on Aug 13, 2019

    @orta
    ContributorAuthor

    Hrm great point - I actually can't think of any reason why as const doesn't cover this other than for the exact case I was looking at (which was to show a particular error message )

    I'm fine with this being considered closed 👍

  4. RyanCavanaugh commented on Aug 14, 2019

    @RyanCavanaugh
    Member

    As an aside I think we're happy with readonly being (unintentionally?) reserved for the time being - who knows what we might want with it later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions