Skip to content

Unsafe type-incompatible assignments should not be allowed #14150

Open
@jaredru

Description

@jaredru

TypeScript Version: 2.1.6

Code

interface StringOnly {
  val: string;
}

interface StringOrNull {
  val: string | null;
}

const obj: StringOnly = { val: "str" };

// should not be allowed
const nullable: StringOrNull = obj;

nullable.val = null;

// obj is now in a bad state

Expected behavior:
The sample should not compile, as it's not safe. Type casts/assertions should be required to override type incompatibility errors here. (Or, of course, cloning the object itself const nullable: StringOrNull = { ...str };).

For comparison, Flow does not allow the sample code.

Actual behavior:
The sample compiles and further accesses of str.val will likely result in exceptions.

EDIT: Removed all references to readonly, as discussion of that modifier is overshadowing the issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions