Skip to content

New rule: unsafe assignment / declaration / return / call #21

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

Closed
danielnixon opened this issue Jun 14, 2020 · 2 comments
Closed

New rule: unsafe assignment / declaration / return / call #21

danielnixon opened this issue Jun 14, 2020 · 2 comments
Labels
help wanted Extra attention is needed

Comments

@danielnixon
Copy link
Owner

danielnixon commented Jun 14, 2020

Prevent this:

type A = { val: string; };
type B = { val: string | number; };

const a: A = { val: "string" };
const b: B = a;

b.val = 3;

console.log(a.val.toUpperCase()); // throws

And this:

interface MutableValue<T> {
    value: T;
}

interface ImmutableValue<T> {
    readonly value: T;
}

let i: ImmutableValue<string> = { value: "hi" };
i.value = "Excellent, I can't change it"; // compile-time error

let m: MutableValue<string> = i;
m.value = "Oh dear, I can change it";

see microsoft/TypeScript#14150 and microsoft/TypeScript#13347

@danielnixon danielnixon added the help wanted Extra attention is needed label Jun 14, 2020
@danielnixon
Copy link
Owner Author

danielnixon commented Jun 14, 2020

So, when comparing the types on either sides of the declaration (or assignment, or return, or call):

  • Both sides readonly (safe because neither can be mutated)
  • Right hand side is an object literal (safe because no reference can be retained to the right hand side) - TODO but what if the object literal sets a property to a value that we do retain a reference to
  • Both sides mutable AND neither side is a type union AND both sides are exactly the same type (safe because mutating one can't break the type of the other)
  • TODO: work out how to handle unions
  • TODO: work out how to handle subtype relationship (argument is a subtype of param)

@danielnixon danielnixon changed the title New rule: invariant mutable properties New rule: unsafe assignment Jun 14, 2020
@danielnixon danielnixon changed the title New rule: unsafe assignment New rule: unsafe assignment / declaration Jun 14, 2020
@danielnixon
Copy link
Owner Author

Initial version of rule landed: 87b978c

@danielnixon danielnixon changed the title New rule: unsafe assignment / declaration New rule: unsafe assignment / declaration / return / call Jun 19, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant