Typescript: Array.prototype.map() allows assigning additional properties to an array of defined type

Created on 22 Jan 2020  路  3Comments  路  Source: microsoft/TypeScript

TypeScript Versions: from 3.5.1 to Nightly (issue not present in 3.3.3)


Search Terms: array map

Expected behavior: Third assignment should raise an error

Actual behavior: Assignment is allowed


Related Issues: No found any

Code

interface A {
    a: 2
}

// 1. Correct: b property is not allowed in type A
const a: A = { a: 2, b: 8 }

// 2. Correct: b property is not allowed in type A
const other: A[] = [{ a: 2, b: 8 }]

// 3. Incorrect (no error): why is b property permitted here?
const array: A[] = [1, 2].map(i => ({ a: 2, b: 8 }))

Output

"use strict";
// 1. Correct: b property is not allowed in type A
const a = { a: 2, b: 8 };
// 2. Correct: b property is not allowed in type A
const other = [{ a: 2, b: 8 }];
// 3. Incorrect (no error): why is b property permitted here?
const array = [1, 2].map(i => ({ a: 2, b: 8 }));

Compiler Options

{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "useDefineForClassFields": false,
    "alwaysStrict": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "downlevelIteration": false,
    "noEmitHelpers": false,
    "noLib": false,
    "noStrictGenericChecks": false,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "esModuleInterop": true,
    "preserveConstEnums": false,
    "removeComments": false,
    "skipLibCheck": false,
    "checkJs": false,
    "allowJs": false,
    "declaration": true,
    "experimentalDecorators": false,
    "emitDecoratorMetadata": false,
    "target": "ES2017",
    "module": "ESNext"
  }
}

Playground Link: Provided

Duplicate

Most helpful comment

Or duplicate of #241

All 3 comments

Duplicate of #33158

The error in 3.3.3 is not the one you're looking for. That error is due to widening of 2 to number; it has nothing to do with the presence of the b property. Even this errors in 3.3.3:

const array: A[] = [1, 2].map(i => ({ a: 2 })); // error!
// Type '{ a: number; }' is not assignable to type 'A'.

In reality the error you expect is not happening because excess property checking only happens in very specific circumstances. See #33158 for more discussion. Good luck!

Or duplicate of #241

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Was this page helpful?
0 / 5 - 0 ratings