Reputation:
I have the following interfaces:
interface Ixy
{
X: string;
Y: string;
}
interface Ixz
{
X: string;
Z: string;
}
This function:
export function update(json: Ixy) {
var a = json.X;
}
The function is called from the following two places:
export function update1(json: Ixy) {
update(json);
}
export function update2(json: Ixz) {
update(json);
}
Can someone explain to me the best way I cand make this work with typescript. Right now update1 is okay but update2 shows that the signature does not match. Is the only way I can fix this to change the type of the json to any or is there a better way to do this?
Upvotes: 2
Views: 92
Reputation: 11294
There are a couple of ways to do it. Probably the best is to create a base interface Ixx
which has the common property X
, then extend it to create Ixy
and Ixz
, and then implement update
with Ixx
as the parameter type:
interface Ixx
{
X: string;
}
interface Ixy extends Ixx
{
Y: string;
}
interface Ixz extends Ixx
{
Z: string;
}
export function update(json: Ixx) {
var a = json.X;
}
export function update1(json: Ixy) {
update(json);
}
export function update2(json: Ixz) {
update(json);
}
This works because Ixy
and Ixz
both extend Ixx
and so would satisfy the condition json is Ixx
. This works with classes extending a base class as well (or classes which extend a base interface).
There's not a lot of literature on TypeScript yet, so perhaps a couple of general introductions to interfaces from other languages will be useful, as this is really a cross-language question about interface use, rather than anything TS-specific.
Java interfaces: http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
C# interfaces: http://www.codeproject.com/Articles/18743/Interfaces-in-C-For-Beginners
Upvotes: 1