2

typescript interface: how to implements the interface which merge function interface and property interface. eg:

interface keyMap {
  name: string;
  mark: number;
}

let keyMapInstance: keyMap = { name: 'John', mark: 85 }

interface development extends keyMap {
  (code: string): void
}

error message

2 Answers 2

1

The problem is that development has both a call signature (which can be satisfied by the function) and members (from inheriting keymap).You can't define such an object in one step in Typescript (or Javascript for that matter). When you assign the function the compiler complains that the properties are missing (as it should since they are not there yet). You could do one of two things:

Use Object.assign to build the object in one step

var me: development = Object.assign((code: string)=> console.log(code), keyMapInstance)

Use a type assertion and finish the initialization later

var me: development = <development>((code)=> console.log(code))
me.mark = 10;
me.name ="";

Variant: Make the fields optional,and finish the initialization later

interface development extends Partial<keyMap> {
    (code: string): void
}

var me: development = (code)=> console.log(code)
me.mark = 10;
me.name ="";
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answering, I understood
0

In the development interface, I believe you're trying to declare a void function that takes a string argument. That should be done like this:

interface development extends keyMap {
  fn: (code: string) => void
}

demo

1 Comment

Actually it depends what he is trying to achieve, it is perfectly valid to have an interface with a call signature as in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.