Skip to content

Compile time comparison of accessors fails to differentiate on setter/getter #49046

New issue

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

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

Already on GitHub? # to your account

Closed
neirfeno opened this issue May 10, 2022 · 4 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@neirfeno
Copy link

Bug Report

πŸ”Ž Search Terms

  • type check read-only accessor
  • compile time check for setter

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type checking of accessors

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

class Immutable {
    get prop(): string {
        return 'foo';
    }
}

class Mutable {
    set prop(value: string) {}
}

class Other {
    get prop2(): string {
        return 'foo';
    }
}

const test = (v: Mutable) => {};

test(new Other());
//Compile error as expected
test(new Immutable());
//No error, but would also expect one

πŸ™ Actual behavior

Other correctly causes a compile error as it does not have prop property. Immutable passes compiler check even though the prop property is read-only (just a get)

πŸ™‚ Expected behavior

I would expect both Other and Immutable to fail the typing of test as neither adhere to the structure of Mutable.

If inside test I try and set v.prop when Immutable is passed in I get a runtime error. I would expect the typing to guard against this.

@fatcerberus
Copy link

This isn’t specific to accessors and happens with readonly properties as well. Unfortunately readonly-ness is a very weak guarantee in TS :(

@mkantor
Copy link
Contributor

mkantor commented May 10, 2022

The other issue is the absence of a writeonly modifier to model properties with setters but no getters. For example, this would ideally be a compile-time error:

const x = { set foo(_x: string) {} }
x.foo = 'ok' // should be allowed
x.foo.includes('yikes') // should not be allowed

@RyanCavanaugh
Copy link
Member

Duplicate #21759 / #18770

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label May 10, 2022
@typescript-bot
Copy link
Collaborator

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

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants