Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript object implementing interface with extra properties error [duplicate]

Tags:

typescript

I'm going through a Pluralsight course on TypeScript and this throws an error, while it is explained to be a valid code in the course.

error TS2322: Type '{ favouriteSport: string; name: string; kids: number; age: number; calcPets: () => number; makeYo...' is not assignable to type 'Person'. Object literal may only specify known properties, and 'favouriteSport' does not exist in type 'Person'.

interface Person{
    age: number,
    name: string,
    kids: number,
    calcPets: ()=> number;
    makeYounger: (years: number) => void;
    greet: (msg: string) => string; 
}

var p: Person = {
    favouriteSport: "tennis",
    name: "Michael",
    kids: 4,
    age: 44,
    calcPets: function(){
        return this.kids * 2;
    },
    makeYounger: function(years: number){
        this.age -= years;
    },
    greet: function(msg: string){
        return msg + ', ' + this.name;
    }
}
like image 983
mishap Avatar asked Oct 01 '15 21:10

mishap


2 Answers

Take a look at this github issue. Looks like the behavior changed in 1.6. My guess is the course you are taking was written before 1.6.

like image 135
leeor Avatar answered Nov 20 '22 06:11

leeor


These types of checks were added recently in 1.6

Starting with 1.6, we’re tightening up some of our object checking rules. [...] You can also suppress this warning by passing the --suppressExcessPropertyErrors compiler option.

http://blogs.msdn.com/b/typescript/archive/2015/09/02/announcing-typescript-1-6-beta-react-jsx-better-error-checking-and-more.aspx

like image 2
thoughtrepo Avatar answered Nov 20 '22 07:11

thoughtrepo