Skip to content

Weird type assertion rules in TypeScript #20849

@SergeyTeplyakov

Description

@SergeyTeplyakov

TypeScript Version: recent master

Consider the following case:

interface I {a: string; b: string;}

// No errors
const x = <I>{a: "1", b: 'sdf', z: 42};

// Error: Object literal may specify only known properties
const x2: I = {a: "1", b: 'sdf', z: 42};

// Error: property 'b' is missing
const x3 = <I>{a: '1', z: 42};

// OK
const x4 = <I>{a: '1'};

So I can't get the assigning rules in TypeScript:

  1. Why the first case with typecast is fine, but the second case with explicit type argument is not? I known that the excessive properties check was added recently, but I can't see why it is not enabled for cast operator as well?
  2. The last two cases are even weirder: why the <I>{a: '1'} is ok, but <I>{a: '1', unknownProp: 2} is not?

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions