Reputation: 395
I would like to implement an interface, but I am having hard time getting the syntax right.
Interface I would like to implement
interface Test {
[name : string] : (source : string) => void;
}
If I understood this right, the interface is basically an object with strings as keys and functions as values.
Any help is much appreciated.
Edit : I get several errors, "incorrect implementation of interface", "index signature is missing", etc,
Playground example : Link
I did not implement the interface, it is from a sdk
Upvotes: 0
Views: 1032
Reputation: 276199
Just add the index signature to the class:
interface Test {
[name: string]: (source: string) => void;
}
class TestClass implements Test {
[name: string]: (source: string) => void; // Add this
getLastName(source: string) {
console.log("test");
}
}
Upvotes: 1
Reputation: 1222
I don't think a class can implement an interface such as this one.
This is more of a "typed object" interface.
You can type an object to specify that it should have a string as keys and a function taking a string and returning nothing as values.
Like so:
let myObj: Test = {
test: (source: string) => { console.log('function returning void'); }
};
Upvotes: 0