TransWikia.com

Why can I assign unknown properties to literal object in typescript?

Stack Overflow Asked by nolan on November 4, 2021

  type ExpectedType = Array<{ name: number, gender?: string }>

  function go1(p: ExpectedType) {

  }  

  function f() {
    const a = [{name: 1, age: 2}]
    go1(a)                   // doesn't complain
    go1([{name: 1, age: 2}]) // complain 'Object literal may only specify known...'
    go1(['no matter'].map(n => ({name: 1, age: 2}))) // doesn't complain
  }

The typescript code is as above, my question is that isn’t the last three lines the same? Why the first line can pass and the second line get a complaint, and the third line get a pass?

Also on the typescript playground:
playground

2 Answers

After some research, I found the answer is in TypeScript's document.

So the difference between the last 3 lines is that: The param in the 2nd line is object literally, while the other 2 not, TypeScript treat literally params and non-literally params differently:

Excess Property Checks

Answered by nolan on November 4, 2021

When assigning var a to the parameter of go1(), it seems like assigning variable a to another para variable. In this case, because type of a is compatible with parameter variable type. But if you change the type to { name: number, gender: string }, you will still have type error.

When assigning a literal object as the parameter, there is no type cast in this case, so the compiler can detect this type error.

More details refer to here.

The basic rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x. For example:

interface Named {
    name: string;
}

let x: Named;
// y's inferred type is { name: string; location: string; }
let y = { name: "Alice", location: "Seattle" };
x = y;

To check whether y can be assigned to x, the compiler checks each property of x to find a corresponding compatible property in y. In this case, y must have a member called name that is a string. It does, so the assignment is allowed.

Answered by Eric on November 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP