Skip to content

Class property types are ignored when passed as an argument object vs. assigned directly #30926

@methodbox

Description

@methodbox

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms:
Class, constructor, ignore.
Code
You can see this code from the Scrimba link below, under the "Playground Link".
This example will type check, as expected, no issues.

class Person {
    firstName: string;
    middleName: string;
    lastName: string;
    
    constructor(data?: any) {
        this.firstName = data.firstName || 'Dylan';
        this.lastName = data.lastName || 'Israel';
        this.middleName = data.middleName;    
    }
}

example1.firstName = 'Dylan';
example1.middleName = 10;  // this will flag in the linter and fail type check as expected
example1.lastName = 'Israel';

With the same code, but passing the object for the new Person, it will not type check:

// ... same code as above

// nothing here will be flagged at all. It also compiles just fine, so it's not just the linter.
const testPerson = new Person({firstName: 10, lastName: false, middleName: 'actually string'})
// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.

Expected behavior:
Class property types would be respected when assigning their values whether passed as an object or assigned individually.

I'm not a TS expert by any means, but this behavior seems contradictory.

Actual behavior:
Class property types are not respected when passed as an argument to a parameter?: any, although they are already assigned on the class.

Playground Link:

I discovered this while taking a intro course on TS here: https://scrimba.com/p/pKwrCg/cbyMBtW

It failed in the linter there, so I reproduced the issue inside VSCode. Both the linter and compiler fail to catch this.

Related Issues:

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