Home > front end >  TypeScript: Property 'formatName' of type '() => string' is not assignable to
TypeScript: Property 'formatName' of type '() => string' is not assignable to

Time:04-21

I did a copy/past of code from a demo example that works, but in my vs code project I get the error: Property 'formatName' of type '() => string' is not assignable to 'string' index type 'string | number'. However, no where in my code am I using “string|number”.

This is the code in the interface file interfaces.ts:

interface Person {
name: string;
age?: number;
formatName: () => string;  
}

export {
  Person
}

And this is the code for the class that implements the person interface (in a separate file):

import { Person } from './interfaces';

class Employee implements Person {
    name: string;
    age: number;
    formatName() {
        return this.name.toUpperCase();
      }      
}

No where do I assign a property of type 'string | number', so how could I get this error?

enter image description here

And as you can see, the compiler doesn’t like it. My tsconfig.json file even matches the one from the demo I got this from which does not have this error.

I went through all the possible answers in stackoverflow and googled this extensively with no success.

Any help would be most appreciated. I’ve been googling this most of the day.

Thank you.

CodePudding user response:

The line:

[key: string ]: string | number;

was the problem. Remove this line and it compiled. Not sure what the original author was doing with it.

CodePudding user response:

The line [key: string]: string | number is messing with your Employee object. Adding that line is effectively saying "Every property in this class with be of type string or number". The function formatName (which in javascript will be a property under the hood), isn't of type string, rather it is a function that returns a string, which is not the same thing, thus your error.

  • Related