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

Readonly object can be used as parameter for function expecting mutable object #23176

Closed
xaviergonz opened this issue Apr 5, 2018 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@xaviergonz
Copy link

xaviergonz commented Apr 5, 2018

TypeScript Version: 2.8.1

Search Terms: mutate readonly immutable mutable

Code

interface Mutable {
  x: number;
}

interface Immutable {
  readonly x: number;
}

function mutate(mut: Mutable) {
  mut.x = 5;
}

function immutate(imm: Immutable) {
  // imm.x = 5; // this does not compile as expected
  mutate(imm); // but this does
}

Expected behavior: There should be a compiler error inside immutate saying that 'imm' cannot be used as a parameter to mutate since 'imm' is readonly while 'mut' is not

Actual behavior: Compiles successfully

Playground Link: https://codesandbox.io/s/vnp9k2z32y

Related Issues:

@xaviergonz
Copy link
Author

xaviergonz commented Apr 5, 2018

Another example

interface Mutable {
  x: number;
}

interface Immutable {
  readonly x: number;
}

const imm: Immutable = {x: 3};
// imm.x = 5; // not allowed, good :D
const mut: Mutable = imm; // allowed :/
mut.x = 5; // allowed :(

// vs

const roA: ReadonlyArray<number> = [5];
// const writeA: number[] = roA; // not allowed, good :D

@mhegazy
Copy link
Contributor

mhegazy commented Apr 5, 2018

Duplicate of #11180

@mhegazy mhegazy marked this as a duplicate of #11180 Apr 5, 2018
@mhegazy mhegazy added the Duplicate An existing issue was already created label Apr 5, 2018
@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@microsoft microsoft locked and limited conversation to collaborators Jul 30, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants