GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Const contexts for literal expressions by ahejlsberg · Pull Request #29510 · microsoft/TypeScript

Conversation

@ahejlsberg

@ahejlsberg Anders Hejlsberg (ahejlsberg) commented Jan 21, 2019

Copy link
Copy Markdown
Member

With this PR we introduce const assertions which favor immutability in the types inferred for literal expressions (inspired by suggestions in #10195, #20195, and #26979). A const assertion is simply a type assertion that uses the reserved word const as the type name:

let x = 10 as const;  // Type 10
let y = <const> [10, 20];  // Type readonly [10, 20]
let z = { text: "hello" } as const;  // Type { readonly text: "hello" }

A const assertion establishes a const context in which

  • string, numeric, and boolean literals have non-widening literals types (see Non-widening explicit literal types #11126),
  • array literals have read-only tuple types (see Improved support for read-only arrays and tuples #29435), and
  • object literals have read-only properties.

Const contexts do not otherwise affect types of expressions, and expressions in const contexts never have a contextual type.

An expression x is said to occur in a const context if x is

  • the operand of a const assertion, or
  • a parenthesized expression that occurs in a const context, or
  • an element of an array literal that occurs in a const context, or
  • the expression of a property assignment in an object literal that occurs in a const context, or
  • a spread expression that occurs in a const context.

Note in particular that const contexts extend into nested array and object literals. For example, the declaration

let obj = { x: 10, y: [20, 30], z: { a: { b: 42 } } } as const;

corresponds to

let obj: {
  readonly x: 10;
  readonly y: readonly [20, 30];
  readonly z: {
    readonly a: {
      readonly b: 42;
    };
  };
};

A const assertion requires the operand to be a string, number, bigint, boolean, array, or object literal, optionally enclosed in one or more levels of parentheses. It is an error to apply a const assertion to expressions of other forms.

Fixes #10195.
Fixes #20195.
Fixes #26979.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

j-oliveras, as-ivanov, KiaraGrouwstra, pelotom, cartant, eps1lon, yortus, strax, s-ve, Kingwl, and 191 more reacted with thumbs up emoji soyFerrero, semyonf, jtschoonhoven, macabeus, Nathan-ZigGameDev, and Enfield-Li reacted with laugh emoji j-oliveras, cpplearner, KiaraGrouwstra, pelotom, Kingwl, zpdDG4gta8XKpMCd, qm3ster, piotrwitek, Jessidhia, styfle, and 72 more reacted with hooray emoji j-oliveras, KiaraGrouwstra, alexrock, doggy8088, Kingwl, zpdDG4gta8XKpMCd, Jessidhia, styfle, cnordhougen, mwilc0x, and 84 more reacted with heart emoji bradenhs, j-oliveras, KiaraGrouwstra, strax, Kingwl, zpdDG4gta8XKpMCd, qm3ster, jwbay, Jessidhia, styfle, and 35 more reacted with rocket emoji Meligy, gabro, Bnaya, danakt, coalman, masterkidan, unao, lai-nam, MikeRyanDev, disjukr, and 5 more reacted with eyes emoji
All reactions
  • 👍 201 reactions
  • 😄 6 reactions
  • 🎉 82 reactions
  • ❤️ 94 reactions
  • 🚀 45 reactions
  • 👀 15 reactions
Anders Hejlsberg (ahejlsberg) added 5 commits January 18, 2019 16:16
@ahejlsberg
Support '<const> xxx' and 'xxx as const'
beb0270
@ahejlsberg
Validate const assertion operand
ec30c20
@ahejlsberg
Accept baseline API changes
980a681
@ahejlsberg
Add tests
2e94f47
@ahejlsberg
Accept baseline changes
dbfef53
@jack-williams

Jack Williams (jack-williams) commented Jan 21, 2019

Copy link
Copy Markdown
Collaborator

Did you consider using const as a hook for enabling deep excess property checking for arbitrary union and intersection types?

Ivkaa and franz-bendezu reacted with thumbs up emoji
All reactions
  • 👍 2 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@j-oliveras

Jordi Oliveras Rovira (j-oliveras) commented Jan 21, 2019

Copy link
Copy Markdown
Contributor

A question:
Will be possible to write:

let obj = {
    x: 10,
    z: { a: { b: 42 } } as const
};

to initialize a type like:

let obj: {
  x: number;
  z: {
    readonly a: {
      readonly b: 42;
    };
  };
};

If yes, probably you want to add a test like that.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pelotom

Tom Crockett (pelotom) commented Jan 21, 2019

Copy link
Copy Markdown

This is AWESOME. Thank you Anders Hejlsberg (@ahejlsberg)!

joshburgess, Bnaya, unao, AlexeyMz, rozzzly, tvedtorama, semyonf, and meghamallya reacted with thumbs up emoji eps1lon, styfle, joshburgess, Bnaya, unao, tvedtorama, and semyonf reacted with hooray emoji
All reactions
  • 👍 8 reactions
  • 🎉 7 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ahejlsberg

Anders Hejlsberg (ahejlsberg) commented Jan 22, 2019

Copy link
Copy Markdown
Member Author

Did you consider using const as a hook for enabling deep excess property checking for arbitrary union and intersection types?

I did not. Can you provide an example of what you mean exactly?

Will be possible to write (object literal with const assertions in some property values)

Yes.

If yes, probably you want to add a test like that.

Sure.

j-oliveras, unao, bhavik3184, and SlurpTheo reacted with thumbs up emoji
All reactions
  • 👍 4 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@jack-williams

Jack Williams (jack-williams) commented Jan 22, 2019

Copy link
Copy Markdown
Collaborator

Anders Hejlsberg (@ahejlsberg)

Currently neither of these give excess property errors:

const u: { x: number } | { y: string } = { x: 42, y: "helloworld" };
const i: { a: { x: number } & { y: string } } & { b: boolean } = { a: { x: 42, y: "y", z: "excess" }, b: true };

Though these EPC bugs are on the backlog to fix for all literals, there are 2 obstacles:

  1. Adding it would be a breaking change (but a good one IMO).
  2. Adding it might introduce a perf. regression. I believe EPC is done today in a cheap way that can quickly prune large union types. I think fixing the general case requires a full relation check; there is no free lunch to be had.

I'm suggesting that maybe these give errors by using const contexts as a marker to enable complete and correct EPC:

const u: { x: number } | { y: string } = { x: 42, y: "helloworld" } as const; // error 'y' is excess (or some better error)
const i: { a: { x: number } & { y: string } } & { b: boolean } = { a: { x: 42, y: "y", z: "excess" }, b: true } as const; // error 'z' is excess

Basically using const contexts as a way to trial full-EPC in a way that does not introduce any breaking changes. If the trial is successful then full-EPC can be rolled out to all literals with const being ahead of the curve; if the trail does not work out then full-EPC can be removed in const contexts in a non-breaking way.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Sheetal Nandi (sheetalkamat) added a commit to microsoft/TypeScript-TmLanguage that referenced this pull request Jan 22, 2019
@sheetalkamat
Add const assertion as per microsoft/TypeScript#29510
b80870c
@pelotom Tom Crockett (pelotom) mentioned this pull request Jan 23, 2019
Suggestion: a way to disable type widening in object literals #20195
Closed
@Meligy

Meligy (Meligy) commented Jan 23, 2019 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Can it be also assumed in certain situations?

Like:

const a: 12; // type is 12
let x = {
  // Can this be `const`? 
  // Either always, or only when it's `readonly x1: a`. It's fine either way.
  x1: a 
};

The situation here being assignment to a constant, and fine to require readonly for this.

Also, one important situation (as mentioned with more details):

function createAction<TType>(type: TType) {
    // Not concerned with return types here, but inferred argument type
    return {
        type: type
    };
}

// Today this gets inferred as string, but can string literal be inferred as itself?
const doStuff = createAction("DO_STUFF");

The situation here being sending a literal (string or number) to a function with argument type being generic and inferred from usage. It'll be nice to avoid const in createAction("DO_STUFF" const).

pleerock, medfreeman, TooTallNate, alessioscalici, and katzensindniedlich reacted with thumbs up emoji
All reactions
  • 👍 5 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@qm3ster

Mihail Malo (qm3ster) commented Jan 23, 2019

Copy link
Copy Markdown

Next step: allowing importing JSON modules as const

pelotom, as-ivanov, karol-majewski, pigoz, s-ve, elektronik2k5, aksjer, KiaraGrouwstra, jarrodldavis, mmis1000, and 53 more reacted with thumbs up emoji fvilante, kohlmannj, locpd, anuraghazra, fargito, scriptype, slifty, piecyk, TD-Yofun, and Sowed reacted with heart emoji cah-sam-beran, kohlmannj, anuraghazra, fargito, scriptype, slifty, and Sowed reacted with rocket emoji
All reactions
  • 👍 63 reactions
  • ❤️ 10 reactions
  • 🚀 7 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@tal

Tal Atlas (tal) commented Jan 24, 2019

Copy link
Copy Markdown

Is the const keyword from somewhere else? To me it's confusing and easy to conflate with the const variable declaration keyword. immutable would be clearer for me.

samhh, stnwk, styfle, Julienng, s-ve, iamakulov, hrajchert, rwaskiewicz, MSakamaki, lehos, and 18 more reacted with thumbs up emoji
All reactions
  • 👍 28 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pelotom

Tom Crockett (pelotom) commented Jan 24, 2019

Copy link
Copy Markdown

Is the const keyword from somewhere else? To me it's confusing and easy to conflate with the const variable declaration keyword. immutable would be clearer for me.

That would require adding a new keyword for dubious benefit. Personally I think readonly would have been preferable to const (since it has the effect of adding readonly modifiers deeply through a tree of types). But const has the advantage of being short 🤷‍♂️

styfle, piotrwitek, as-ivanov, zpdDG4gta8XKpMCd, vitaliy-bobrov, hrajchert, stnwk, elektronik2k5, levenleven, pleerock, and 8 more reacted with thumbs up emoji
All reactions
  • 👍 18 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pelotom

Tom Crockett (pelotom) commented Jan 24, 2019

Copy link
Copy Markdown

Maybe literal would do it justice?

let x = 10 as literal; 
const y = 10 as literal; 

But it was already a literal, before you added as literal...

karol-majewski and VGamezz19 reacted with thumbs up emoji
All reactions
  • 👍 2 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@zpdDG4gta8XKpMCd

ZpdDG4gta (zpdDG4gta8XKpMCd) commented Jan 24, 2019 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

be it a wanker i would not say a thing, but sure let's nitpick and bike shed this thing to the bone, because we can and it's just useless otherwise

stnwk, agos, elektronik2k5, fleebeee, sylvainpolletvillard, ducin, fforres, KewinDousse, SpencerPark, Dean177, and 8 more reacted with thumbs down emoji IllusionMH, panoply, and adaam2 reacted with laugh emoji stnwk and samhh reacted with confused emoji
All reactions
  • 👎 18 reactions
  • 😄 3 reactions
  • 😕 2 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ducin

Tomasz Ducin (ducin) commented Jan 24, 2019

Copy link
Copy Markdown

Question: if the as const clause recursively adds readonly to object literals, why not calling it as readonly? Not a big issue, but introduces some ambiguity with the native ES6 const which has slightly different meaning than TS' readonly

piotrl, styfle, rauschma, lehos, luthfianto, elektronik2k5, fleebeee, MadaraUchiha, tomblachut, masterkidan, and 11 more reacted with thumbs up emoji
All reactions
  • 👍 21 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@zpdDG4gta8XKpMCd

ZpdDG4gta (zpdDG4gta8XKpMCd) commented Jan 24, 2019

Copy link
Copy Markdown

to those who believes in readonly modifiers, will it make your array properties readonly "deeply through a tree of types"?

pleerock reacted with eyes emoji
All reactions
  • 👀 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@joshburgess

Josh Burgess (joshburgess) commented Jan 25, 2019 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Anders Hejlsberg (@ahejlsberg) Would there be any way to dynamically concatenate two literal types to produce a new literal type using this const context?

For example, in a function like...

const concatLiterals = <A extends string, B extends string>(a: A, b: B) =>
  `${a}{b}` as const // or (a + b) as const

I'm assuming the dynamic nature of the above here would prevent this from working, and it would still widen the type to string, but this capability is something I've wanted for a while.

It would be great to have some sort of type-level concat helper for literals like this.... so that you could do something like:

(a + b) as (const: A + B)

or

`${a}{b}` as (const: ConcatLit<A, B>)

or something along those lines.

interphx, Reshetnyak, and anuraghazra reacted with thumbs up emoji
All reactions
  • 👍 3 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pelotom

Tom Crockett (pelotom) commented Jan 25, 2019 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Apparently as readonly instead of as const was considered and decided against, see the meeting notes. I understand the reasoning, but I still think as readonly is more intuitive 😛

DanielRosenwasser, samhh, antoinebrault, cvx, SpencerPark, aaronbeall, tiagob, and evangalen reacted with thumbs up emoji
All reactions
  • 👍 8 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@DanielRosenwasser

Daniel Rosenwasser (DanielRosenwasser) commented Jan 25, 2019 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

I agree with as const being kind of confusing. Maybe the only reason I don't feel as strongly against it is the explanation itself is relatively consistent with the current distinction of const and readonly.

I suspect that we'll end up with a quick fix like Did you mean 'as const'? when someone writes as readonly.

samhh, styfle, itsMapleLeaf, interphx, and doczi-dominik reacted with thumbs up emoji
All reactions
  • 👍 5 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@zpdDG4gta8XKpMCd

ZpdDG4gta (zpdDG4gta8XKpMCd) commented Jan 25, 2019

Copy link
Copy Markdown

oh let's not forget what readonly really is #13002

DanielRosenwasser, samhh, and WhiteAbeLincoln reacted with laugh emoji
All reactions
  • 😄 3 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@DanielRosenwasser

Daniel Rosenwasser (DanielRosenwasser) commented Jan 25, 2019 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

Somehow I knew exactly what you linked to before I clicked on it.

samhh, gigobyte, and jcalz reacted with laugh emoji
All reactions
  • 😄 3 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@RyanCavanaugh Ryan Cavanaugh (RyanCavanaugh) assigned Anders Hejlsberg (ahejlsberg) Jan 25, 2019
@Bnaya

Bnaya Peretz (Bnaya) commented Jan 25, 2019

Copy link
Copy Markdown

This is probably out of the scope, but:
it will be nice to have a way to also "kill" methods that mutating objects in place.
Such as: Array.sort, Array.splice, Date.setDate

IanYates, interphx, and begininend reacted with thumbs up emoji
All reactions
  • 👍 3 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@esamattis Esa-Matti Suuronen (esamattis) mentioned this pull request Jan 25, 2019
Suggestion: DeepReadonly<T> type #13923
Open
@elektronik2k5

Nick Ribal (elektronik2k5) commented Jan 25, 2019

Copy link
Copy Markdown

+1 for as readonly because that's what it actually does.
TypeScript already has a high syntax overhead and adding more cognitive load by requiring the user to keep in mind how readonly thing translates and relates to thing as const should be avoided.

piotrwitek, stnwk, MadaraUchiha, samhh, cshaa, styfle, mattleff, mpawelski, SpencerPark, simonsarris, and 4 more reacted with thumbs up emoji
All reactions
  • 👍 14 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@masterkidan

Mukundan Kidambi (masterkidan) commented Jan 25, 2019

Copy link
Copy Markdown

A question regarding this....
One of the usages of the Readonly type is to allow methods to return a Readonly object like so

interface foo {
   bar: string
}
function foobar(): ReadonlyArray<foo> {
}

Is it possible to return something like so

function foobar(): foo as const {
}

Would really like to have a use case like the above included as well, as it would help a lot with immutability.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@MartinJohns Martin Johns (MartinJohns) mentioned this pull request Jun 27, 2019
Type inference for constant objects with string literal types #32139
Closed
4 of 5 tasks
@rjamesnw

James (rjamesnw) commented Jul 14, 2019 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Is there a way to allow constant string to represent string literals? For example:

const moduleName = "../../../Project/src/Mod";

async function doSomething() {
    var mod = await import(moduleName); // (works only if a string literal at the moment)
}

In the case above, "mod" is of type "any" because the compiler doesn't recognize the string literal in the constant moduleName (for literal strings, the types are correctly pulled). I'm not sure if this was an oversight, but it makes sense to allow it, since constant strings cannot be reassigned. The only workaround is to wrap await import("../../../Project/src/Mod"); in a function:

async function getMod() { return import("../../../Project/src/Mod"); }
async function doSomething() {
    var mod = await getMod(); // (method required since const strings cannot be used to import module type)
}    

I may also add, it seems very difficult to import namespaces using dynamic imports, which I think is another terrible oversight.

async function doSomething() {
    var mod = await import("../../../Project/src/Mod"); // (forced to use a string literal to get typings)
    var o: mod.SomeClass; // ERROR, cannot find namespace 'mod'
    // var o: InstanceType<typeof mod.SomeClass>; // workaround1
    // var o: import("../../../Project/src/Mod").SomeClass; // workaround2 (who wants to keep typing full paths? A const string would be nice here.)
}

That doesn't even make sense. A namespace, while a type, is still a reference under the hood, and thus should still be importable dynamically somehow; perhaps like:

async function doSomething() {
    import mod = await import("../../../Project/src/Mod"); // (forced to use a string literal to get typings)
    var o: mod.SomeClass;
}

I think all this would aim to better support dynamic imports "on demand" instead of modules forcibly loading every single module when some may not be needed at all, It could also help promote faster initial page loads in many cases. ;)

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@Meligy

Meligy (Meligy) commented Jul 15, 2019

Copy link
Copy Markdown

James (@rjamesnw) since this PR is already merged I don't expect that you can get traction for anything new, but this is a good one actually. Can you please open a new issue for it? Thanks.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@rjamesnw

James (rjamesnw) commented Jul 15, 2019 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

You’re right, sorry, it also occurred to me and I was going to get to doing so asap. ;)

Update: Issue created: #32401

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@jodonnell Jacob O'Donnell (jodonnell) mentioned this pull request Jul 19, 2019
TypeError with CacheLocation syncweek-react-aad/react-aad#95
Open
@wincent Greg Hurrell (wincent) mentioned this pull request Aug 2, 2019
feat(card): create CardWithFile high-level component liferay/clay#2208
Merged
Quique Fdez Guerra (CKGrafico) added a commit to CKGrafico/create-react-app that referenced this pull request Aug 9, 2019
@CKGrafico
Using yarn vs npm with typescript docs
d3120dc
When we want to use other TypeScript version and we do:
`npm install [email protected] -D` 
But when we use new features like const casting microsoft/TypeScript#29510 it does not compile.
Instead of that if we use:
`yarn add [email protected]`
Everything works
@CKGrafico Quique Fdez Guerra (CKGrafico) mentioned this pull request Aug 9, 2019
Using yarn vs npm with typescript docs react/create-react-app#7493
Closed
@millsp pierre (millsp) mentioned this pull request Sep 29, 2019
Narrow type of variable when declared as literal (also tuples) #16896
Open
@tmlayton Tim Layton (tmlayton) mentioned this pull request Feb 27, 2020
[Color system] Icon Shopify/polaris-react-archive#2781
Merged
4 tasks done
@DragorWW Sergey Andreev (DragorWW) mentioned this pull request Feb 28, 2020
[Typescript] enum as const: add support const assertions from TypeScript 3.4 dotansimha/graphql-code-generator#3569
Merged
@ahejlsberg Anders Hejlsberg (ahejlsberg) mentioned this pull request Jul 27, 2020
Literal narrowing lost without explicit const assertion #39763
Closed
@vnues 落落落洛克 (vnues) mentioned this pull request Sep 13, 2021
typescript中的as const vnues/blog#17
Open
Matthew Robertson (matthewrobertson) added a commit to GoogleCloudPlatform/functions-framework-nodejs that referenced this pull request Sep 22, 2021
@matthewrobertson
refactor: use a union type for SignatureType
941f548
This commit refactors the SignatureType enum into an array of strings
declared [as const](microsoft/TypeScript#29510).
This allows the SignatureType type to be expressed as a union type,
which works a bit better when parsing a users provided string.

This is some simple refactoring in preparation for declarative function
signatures.
@matthewrobertson Matthew Robertson (matthewrobertson) mentioned this pull request Sep 22, 2021
refactor!: use a union type for SignatureType GoogleCloudPlatform/functions-framework-nodejs#331
Merged
Matthew Robertson (matthewrobertson) added a commit to GoogleCloudPlatform/functions-framework-nodejs that referenced this pull request Sep 23, 2021
@matthewrobertson
refactor!: use a union type for SignatureType
9109288
This commit refactors the SignatureType enum into an array of strings
declared [as const](microsoft/TypeScript#29510).
This allows the SignatureType type to be expressed as a union type,
which works a bit better when parsing a users provided string.

This is some simple refactoring in preparation for declarative function
signatures.

BREAKING CHANGE: exported SignatureType type is converted from an enum
to a union type
Matthew Robertson (matthewrobertson) added a commit to GoogleCloudPlatform/functions-framework-nodejs that referenced this pull request Sep 23, 2021
@matthewrobertson
refactor!: use a union type for SignatureType (#331)
9cf46ed
This commit refactors the SignatureType enum into an array of strings
declared [as const](microsoft/TypeScript#29510).
This allows the SignatureType type to be expressed as a union type,
which works a bit better when parsing a users provided string.

This is some simple refactoring in preparation for declarative function
signatures.

BREAKING CHANGE: exported SignatureType type is converted from an enum
to a union type
@release-please release-please Bot mentioned this pull request Sep 23, 2021
chore: release 2.0.0 GoogleCloudPlatform/functions-framework-nodejs#332
Merged
@whzx5byb whzx5byb mentioned this pull request Mar 24, 2022
Const primitive value type getting lost? #48402
Closed
@AliN11

Ali Nazari (AliN11) commented Apr 24, 2022 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Why would someone use let for declaring a variable which is typed with as const?

let numbers = [1, 2, 3] as const;
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@MartinJohns Martin Johns (MartinJohns) mentioned this pull request May 21, 2022
Support exact matching array types from JSON files #49194
Closed
5 tasks done
@aaronccasanova Aaron Casanova (aaronccasanova) mentioned this pull request May 31, 2022
docs: add example example with code from README/documentation pkgjs/parseargs#130
Merged
@BeautyInNorth

BeautyInNorth commented Jun 23, 2022

Copy link
Copy Markdown

Excuse me,why is the error reported?

const arr = [
  { age: 12, fruits: 'apple' },
  { age: 16, fruits: 'cherry' },
  { fruits: 'banana' },
] as const

type Fruits = typeof arr[number]['fruits']

arr.map(({ age, fruits }) => {
  //Property 'age' does not exist on type 
  //'{ readonly age: 12; readonly fruits: "apple"; } | { readonly age: 16; readonly fruits: "cherry"; } | { readonly fruits: "banana"; }'.
  console.log(age)
})
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pelotom

Tom Crockett (pelotom) commented Jun 23, 2022

Copy link
Copy Markdown

Excuse me,why is the error reported?

Because not every element of the array has an age property.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@AliN11

Ali Nazari (AliN11) commented Jun 26, 2022 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

I found out that as const does not work after a variable has been declared:

let x = 12;
x = 2 as const;

x = 5;

console.log(x); // 5

Also you'll get no error if the reassigned value is like the previous value:

let x = [1, 2] as const;

x = [1, 2]; // works
marckassay and kohsine reacted with thumbs up emoji
All reactions
  • 👍 2 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@brandonpittman

Brandon Pittman (brandonpittman) commented Nov 9, 2022

Copy link
Copy Markdown

Excuse me,why is the error reported?

Because not every element of the array has an age property.

Is there a way to type an array of objects declared using as const if some of the objects lack properties that other objects have?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ahejlsberg Anders Hejlsberg (ahejlsberg) mentioned this pull request Dec 12, 2022
const modifier on type parameters #51865
Merged
@andretchen0 andretchen0 mentioned this pull request Jul 25, 2023
Improve types FreezingMoon/AncientBeast#2447
Merged
@cshaa

csha (cshaa) commented Aug 8, 2024

Copy link
Copy Markdown

image

While as const turned out to be a really nice feature, it does have its drawbacks.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@microsoft Microsoft (microsoft) locked as resolved and limited conversation to collaborators May 26, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Reviewers

@RyanCavanaugh Ryan Cavanaugh (RyanCavanaugh) RyanCavanaugh approved these changes
@DanielRosenwasser Daniel Rosenwasser (DanielRosenwasser) Awaiting requested review from DanielRosenwasser

Uh oh!

There was an error while loading. Please reload this page.

Assignees

@ahejlsberg Anders Hejlsberg (ahejlsberg)

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Type literal assertion as const to prevent type widening Suggestion: a way to disable type widening in object literals Syntax for hinting literal type inference

Uh oh!

There was an error while loading. Please reload this page.

20 participants

@ahejlsberg @jack-williams @j-oliveras @pelotom @Meligy @qm3ster @tal @zpdDG4gta8XKpMCd @ducin @joshburgess @DanielRosenwasser @Bnaya @elektronik2k5 @masterkidan @aleclarson @karol-majewski @iztsv @vmasek @KiaraGrouwstra @MastroLindus
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.