Git Product home page Git Product logo

typescript's Issues

Add --strictAssignments flag to prevent unsafe code from aliasing assignments

Search Terms

microsoft#1394 is related but suggests adding new keywords whereas this feature request doesn't require new keywords.

Suggestion

Add a --strictAssignments flag which would force all variables appearing on the right side of an assignment expression to be invariant with the corresponding type on the left side of an assignment expression. If the left size is readonly, the assignment will be treated as covariant.

Use Cases

This feature would be helpful when writing safe code by protecting against mutating arrays or objects to contain data that doesn't match the defined type. This can cause runtime errors when using an object of a different type while assuming it was the original type.

// Motivating example
class Animal {}
class Cat { purr() {} }
class Dog { bark() {} }

const cats: Cat[] = [new Cat];
const animals: Animal[] = cats;

animals.push(new Dog);
cats.forEach(cat => cat.purr());  // TypeError thrown: .purr() not present on cat

Examples

// Arrays
const cats: Cat[] = [new Cat];

const animals: Animal[] = cats; // error: alias assignments are invariant
const animals: Animal[] = [new Cat];  // okay: covariant is safe since source is a literal
const animals: ReadonlyArray<Animal> = cats; // okay: covariant is safe since target is readonly

// Simple objects
type CatNode = { animal: Cat };
type AnimalNode = { animal: Animal };

const catNode: CatNode = { animal: new Cat };

const animalNode: AnimalNode = catNode; // error
const animalNode: AnimalNode = { animal: new Cat }; // okay
const animalNode: AnimalNode = { animal: cat }; // okay
const animalNode: Readonly<AnimalNode> = catNode;  // okay

// Nested objects
type CatsNode = { animals: Cat[] };
type AnimalsNode = { animals: Animal[] };
type ReadonlyAnimalsNode = { animals: ReadonlyArray<Animal> };

const catsNode: CatNode = { animals: [new Cat] };
const cats: Cat[] = [new Cat];

const animalsNode: AnimalNode = catsNode; // error
// prevents animalsNode.animals = [new Dog] which would conflict 
// with CatsNode's definition of its animals property

const animalsNode: AnimalNode = { animal: [new Cat] }; // okay
// okay since we're not storing [new Cat] in a variable typed as a Cat[]

const animalsNode: AnimalNode = { animal: cats }; // error
// prevents animalsNode.animals.push(new Dog) which would add
// a Dog to cats array

const animalsNode: ReadonlyAnimalsNode = { animals: cats }; // okay
// okay since the animals property is a readonly array and we are unable
// to add new elements to it.

const animalsNode: ReadonlyAnimalsNode = catsNode; // error
// prevents animalsNode.animals = [new Dog] which would conflict 
// with CatsNode's definition of its animals property

const animalsNode: Readonly<ReadonlyAnimalsNode> = catsNode; // okay
// prevents both setting animals property to different from Cats[] and
// prevents adding a Dog to the animals array which is typed as a Cats[]
// on the right side

const animalsNode: Readonly<AnimalsNode> = catsNode;  // error
// while making AnimalsNode readonly prevents the reassignment of animals
// to something other than Cat[], it's still possible to push a Dog to catsNode's
// animals array.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code. This change is opt in except for users using --strict would get this behavior. My assumption in this is that users wanting strict behavior would probably appreciate additional checks that improve safety.

  • This wouldn't change the runtime behavior of existing JavaScript code. This is a compile time check only. It doesn't affect the output of the emitter.

  • This could be implemented without emitting different JS based on the types of the expressions. No change to emitter output.

  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)

  • This feature would agree with the rest of TypeScript's Design Goals. In particular it checks the "Produce a language that is composable and easy to reason about." box. The fact that we can write code that will subvert guarantees about the types stored within variables and objects make it hard to reason about code.

Add --strictCallArgs flag to prevent unsafe mutation of function call args

Search Terms

microsoft#1394 is related but suggests adding new keywords whereas this feature request doesn't require new keywords.

Suggestion

Add a --strictCallArgs compiler flag which would ensure that all args that are variables appearing as args to a function calls be invariant with the type of their function param.

Use Cases

This feature would be useful when writing code that uses functions because it would provide a way to detect unsafe function calls which might mutate a value to be a different type.

Motivating example:
class Animal {}
class Cat { purr() {} }
class Dog { bark() {} }

function foo(animals: []) {
   animals.push(new Dog);
}

const cats: Cat[] = [new Cat];

foo(cats); 
cats.forEach(cat => cat.purr());  // TypeError thrown: .purr() not present on cat

Examples

const cats: Cat[] = [new Cat];

function foo(animals: []) {
   animals.push(new Dog);
}
foo(cats); // error, prevent a Dog from getting added to cats
foo([new Cat]);  // okay

function readonlyFoo(animals: ReadonlyArray<Animal>) {
   // can't mutate animals
}
readonlyFoo(cats); // okay since readonlyFoo can't mutate animals param
type CatNode = { animal: Cat };
type AnimalNode = { animal: Animal };

const catNode = { animal: new Cat };

function bar(node: AnimalNode) {
   node.animal = new Dog;
}
bar(catNode); // error, prevent catNode.animal from becoming a Dog
bar({ animal: new Cat }); // okay, no other references to the new Cat

function readonlyBar(node: Readonly<AnimalNode>) {
   // can't mutate node and change the animal property
}
readonlyBar(catNode); // okay since readonlyBar can't mutate node param
type CatsNode = { animals: Cat[] };
type AnimalsNode = { animals: Animal[] };
type ReadonlyAnimalsNode = { animals: ReadonlyArray<Animal> };

const catsNode = { animals: [new Cat] };
const cats = [new Cat];

function baz(node: AnimalsNode) {
   node.animals = [new Dog];
   node.animals.push(new Dog);
}

baz(catsNode); // error
// prevents both replacing catNode.animals with a new array containing 
// a Dog or adding a Dog to the animals property

baz({ animals: cats }); // error
// prevent adding a dog to the animals property

baz({ animals: [new Cat] }); // okay, no other references to the array of Cats

function readonlyBaz(node: Readonly<AnimalsNode>) {
   // can't set node.animals to a new array
   node.animals.push(new Dog);
}
readonlyBaz(catsNode); // error, prevent adding a Dog to catsNode.animals
readonlyBaz({ animals: cats }); // error, prevent adding a dot to cats
readonlyBaz({ animals: [new Cat] }); // okay

function qux(node: ReadonlyAnimalsNode) {
   node.animals = [new Dog];
   // can't add a Dog to node.animals
}
qux(catsNode); // error
// prevent replacing catNode.animals with a new array containing a Dog

qux({ animals: cats }); // okay
// replacing animals with a new array is fine since { animal: cats } is literal

qux({ animals: [new Cat] }); // okay

function readonlyQux(node: Readonly<ReadonlyAnimalsNode>) {
   // can't set node.animals to a new array
   // can't add a Dog to node.animals
}

readonlyQux(catsNode); // okay
readonlyQux({ animals: cats }); // okay
readonlyQux({ animals: [new Cat] }); // okay

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code. This change is opt in except for users using --strict would get this behavior. My assumption in this is that users wanting strict behavior would probably appreciate additional checks that improve safety.

  • This wouldn't change the runtime behavior of existing JavaScript code. This is a compile time check only. It doesn't affect the output of the emitter.

  • This could be implemented without emitting different JS based on the types of the expressions. No change to emitter output.

  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)

  • This feature would agree with the rest of TypeScript's Design Goals.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.