Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object.freeze should infer narrow types on immediate properties #45341

Closed
dwjohnston opened this issue Aug 6, 2021 · 4 comments
Closed

Object.freeze should infer narrow types on immediate properties #45341

dwjohnston opened this issue Aug 6, 2021 · 4 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@dwjohnston
Copy link

dwjohnston commented Aug 6, 2021

Bug Report

🔎 Search Terms

Object.freeze narrow string

🕗 Version & Regression Information

Apologies, this doesn't look like a regression, but I couldn't find this in any of the FAQs. If this is a duplicate or a 'won't do' can someone point me to it?

⏯ Playground Link

Playground link with relevant code

💻 Code

type SomeObject = {
    userType: "admin" | "user"; 
}


function usesAnObject(obj: SomeObject) {

}




const theObject5 = Object.freeze({
    userType: "admin"
}); 

usesAnObject(theObject5); // Argument of type 'Readonly<{ userType: string; }>' is not assignable to parameter of type 'SomeObject'.

🙁 Actual behavior

In this code the type of the userType property is widened to string.

🙂 Expected behavior

The type should be kept as the narrower "admin" as it is not possible for that property to be reassigned.

@dwjohnston dwjohnston changed the title Object.freeze should derive narrow types Object.freeze should infer narrow types on immediate properties Aug 6, 2021
@fatcerberus
Copy link

Use as const. The object literal is getting widened before Object.freeze() sees it.

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Aug 6, 2021
@RyanCavanaugh
Copy link
Member

We don't have hardcoded logic specifically for Object.freeze; it's just another function.

@jcalz
Copy link
Contributor

jcalz commented Aug 7, 2021

If we had #30680 then the signature to Object.freeze() could use it; without it, there are dirty tricks that could work, but I don't think anyone wants to see them in the standard TypeScript library.

@typescript-bot
Copy link
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

5 participants