通用介面
宣告通用介面
interface IResult<T> {
wasSuccessfull: boolean;
error: T;
}
var result: IResult<string> = ....
var error: string = result.error;
具有多個型別引數的通用介面
interface IRunnable<T, U> {
run(input: T): U;
}
var runnable: IRunnable<string, number> = ...
var input: string;
var result: number = runnable.run(input);
實現通用介面
interface IResult<T>{
wasSuccessfull: boolean;
error: T;
clone(): IResult<T>;
}
使用泛型類實現它:
class Result<T> implements IResult<T> {
constructor(public result: boolean, public error: T) {
}
public clone(): IResult<T> {
return new Result<T>(this.result, this.error);
}
}
使用非泛型類實現它:
class StringResult implements IResult<string> {
constructor(public result: boolean, public error: string) {
}
public clone(): IResult<string> {
return new StringResult(this.result, this.error);
}
}