Skip to content

POC: Make assignment expressions and function calls safe #1

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
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions foo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
class Animal {}
class Dog extends Animal { bark() {} }
class Cat extends Animal { purr() {} }

const cats: Cat[] = [new Cat];
const goodAnimals: Animal[] = [new Cat, new Dog];
const readonlyAnimals: ReadonlyArray<Animal> = cats;
const badAnimals: Animal[] = cats; // error

const foo = (animals: Animal[]) => {};
foo(goodAnimals);
foo([new Cat]);
foo(cats); // error

const bar = (animals: ReadonlyArray<Animal>) => {};
bar(goodAnimals);
bar(cats);
bar([new Cat]);

badAnimals.push(new Dog);
// Unsound and bad
cats.forEach(cat => cat.purr());

type NumberNode = { id: number };
type MixedNode = { id: number | string };
const numNode: NumberNode = { id: 5 };
const goodMixedNode: MixedNode = { id: 5 };
const badMixedNode: MixedNode = numNode; // error
badMixedNode.id = "five"; // whoops, now node0 has a string for its "id"
const readonlyMixedNode: Readonly<MixedNode> = numNode; // this is okay

const mixedNodeFunc = (node: MixedNode) => {};
mixedNodeFunc(goodMixedNode);
mixedNodeFunc(numNode); // error, mixedNodeFunc could mutate numNode to set "id" to be a string
mixedNodeFunc({ id: 5 });

const readonlyMixedNodeFunc = (node: Readonly<MixedNode>) => {};
readonlyMixedNodeFunc(goodMixedNode);
readonlyMixedNodeFunc(numNode);
readonlyMixedNodeFunc({ id: 5 });

type CatNode = { animal: Cat };
type AnimalNode = { animal: Animal };
const catNode: CatNode = { animal: new Cat };
const goodAnimalNode: AnimalNode = { animal: new Cat };
const badAnimalNode: AnimalNode = catNode; // error

// const a: number = 5;
// const b: number | string = a;
Loading