[英]Implement interface with the type of a subclass in typescript
如何在 Typescript 中實現下面的接口,避免注釋錯誤?
這些是從 angular 導入的類:
這是在接口中定義的基礎 class:
export declare abstract class LocationStrategy {
abstract path(includeHash?: boolean): string;
abstract prepareExternalUrl(internal: string): string;
abstract pushState(state: any, title: string, url: string, queryParams: string): void;
abstract replaceState(state: any, title: string, url: string, queryParams: string): void;
abstract forward(): void;
abstract back(): void;
abstract onPopState(fn: LocationChangeListener): void;
abstract getBaseHref(): string;
static ɵfac: ɵngcc0.ɵɵFactoryDef<LocationStrategy, never>;
}
這是接口實現中用到的class
export declare class PathLocationStrategy extends LocationStrategy {
private _platformLocation;
private _baseHref;
constructor(_platformLocation: PlatformLocation, href?: string);
onPopState(fn: LocationChangeListener): void;
getBaseHref(): string;
prepareExternalUrl(internal: string): string;
path(includeHash?: boolean): string;
pushState(state: any, title: string, url: string, queryParams: string): void;
replaceState(state: any, title: string, url: string, queryParams: string): void;
forward(): void;
back(): void;
static ɵfac: ɵngcc0.ɵɵFactoryDef<PathLocationStrategy,[null, { optional: true }]>;
static ɵprov: ɵngcc0.ɵɵInjectableDef<PathLocationStrategy>;
}
我的代碼:
我真的需要在實現中提供類型,這些類型將用作標記。 environment
常量是正確的,但是我需要創建幾個類似的,所以我想為它創建一個接口。
所以我需要的是在不修改locationStrategy: PathLocationStrategy
的情況下正確推斷IEnvironment
接口。
import { LocationStrategy, PathLocationStrategy } from '@angular/common';
export interface IEnvironment {
production: boolean;
locationStrategy: LocationStrategy;
// This is just a test trying to infer what the interface should look like.
locationStrategy1: typeof LocationStrategy;
}
const environment: IEnvironment = {
production: false,
// Type 'typeof PathLocationStrategy' is missing the following properties from type
// 'LocationStrategy': path, prepareExternalUrl, pushState, replaceState, and 4 more.ts(2740)
locationStrategy: PathLocationStrategy,
// Type 'typeof PathLocationStrategy' is not assignable to type 'typeof LocationStrategy'.
// Types of construct signatures are incompatible.
// Type 'new (_platformLocation: PlatformLocation, href?: string | undefined)
// => PathLocationStrategy' is not assignable to type 'abstract new () => LocationStrategy'.ts(2322)
locationStrategy1: PathLocationStrategy,
};
以下是我找到的解決方案。
// @angular/core
export declare const Type: FunctionConstructor;
export declare interface Type<T> extends Function {
new (...args: any[]): T;
}
解決方案:
import { LocationStrategy } from '@angular/common';
import { Type } from '@angular/core';
export interface IEnvironment {
production: boolean;
locationStrategy: Type<LocationStrategy>;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.