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

freezing indexed objects causes compile error #12712

Closed
kieferrm opened this issue Dec 7, 2016 · 3 comments
Closed

freezing indexed objects causes compile error #12712

kieferrm opened this issue Dec 7, 2016 · 3 comments
Assignees
Labels
Fixed A PR has been merged for this issue Suggestion An idea for TypeScript

Comments

@kieferrm
Copy link
Member

kieferrm commented Dec 7, 2016

See microsoft/vscode#16819

TypeScript Version: typescript@2.1.4-insiders.20161206

  • VSCode Version: Code - Insiders 1.8.0-insider (0d65ced0fa7398dc9d50c39a23a2a8cc8406ff18, 2016-12-07T07:05:09.124Z)
  • OS Version: Darwin x64 15.6.0

Code

export interface Foo {
	property: boolean;
	[key: string]: any;
}

function freezer(bar: Foo): Foo {
	return Object.freeze(bar);
}

freezer(null);

Expected behavior:
No erros are shown in the vscode editor

Actual behavior:
screen shot 2016-12-07 at 9 36 11 am

The error goes away if property or the index is removed from Foo.

@mhegazy mhegazy added In Discussion Not yet reached consensus Bug A bug in TypeScript labels Dec 7, 2016
@mhegazy mhegazy self-assigned this Dec 7, 2016
@mhegazy mhegazy added Suggestion An idea for TypeScript and removed Bug A bug in TypeScript labels Dec 7, 2016
@mhegazy
Copy link
Contributor

mhegazy commented Dec 7, 2016

The issue is that keyof Foo in the exampe above is string and no"property" | string. we would like to try changing this behavior.

@kieferrm
Copy link
Member Author

kieferrm commented Dec 7, 2016

@mhegazy I'm not sure I understand if that implies that the code example is incorrect. If so, can you point out how the code should be changed to avoid the error?

@mhegazy
Copy link
Contributor

mhegazy commented Dec 7, 2016

freeze is defined to use a mapped Readonly. Mapped types generate a copy of the type using known keys (i.e. keyof Foo in this example). Since it is "property" | string and string is a super type of "property", "property" gets lost, and the new type created is missing the known property..

so long story short, this behaves as designed, but we need to revisit the design.

for now, you can cast the result to Foo, e.g.

function freezer(bar: Foo): Foo {
	return <Foo>Object.freeze(bar);
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Fixed A PR has been merged for this issue Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants