Typescript - 从接口实现匿名对象[重复]
Posted
技术标签:
【中文标题】Typescript - 从接口实现匿名对象[重复]【英文标题】:Typescript - Implementation of an anonymous object from an interface [duplicate] 【发布时间】:2020-03-06 23:39:11 【问题描述】:我对 Typescript 还是很陌生,我在接口实现方面几乎没有遇到任何问题。
我拥有的界面(来自 d3.js 类型):
export interface AxisScale<Domain>
(x: Domain): number | undefined;
domain(): Domain[];
range(): number[];
copy(): this;
bandwidth?(): number;
// TODO: Reconsider the below, note that the compiler does not differentiate the overloads w.r.t. optionality
// ticks?(count?: number): Domain[];
// ticks?(count?: AxisTimeInterval): Date[];
// tickFormat?(count?: number, specifier?: string): ((d: number) => string);
// tickFormat?(count?: number | AxisTimeInterval, specifier?: string): ((d: Date) => string);
这就是我尝试实现接口的方式:
export class Axis implements AxisScale<number>
domain(): (number)[]
return [5];
range(): number[]
return [5, 10]
copy(): this
return this;
bandwidth?(): number
return d3.scaleBand().align();
side: 't' | 'b' | 'l' | 'r';
color: string = "#000000";
padding: number;
margin: Margin;
当我保存文件并收到此错误时:
Type 'Axis' provides no match for the signature '(x: number): number'.
如何在我的类中实现匿名对象((x: Domain): number | undefined;
)?
【问题讨论】:
【参考方案1】:(x: Domain): number | undefined;
描述了一个函数签名。类不能实现包含索引签名的接口,只有函数可以:
export interface AxisScale<Domain>
(x: Domain): number | undefined;
domain(): Domain[];
range(): number[];
copy(): this;
bandwidth?(): number;
const CreateAxis = function (): AxisScale<number>
function Axis(this: typeof Axis, x: number): number
return 0
Axis.domain = function (): number[]
return [5];
Axis.range = function (): number[]
return [5, 10]
Axis.copy = function <T>(this: T): T
return this;
// side: 't' | 'b' | 'l' | 'r';
Axis.color= "#000000";
Axis.padding = 0
return Axis;
;
let axis = CreateAxis();
axis(10)
axis.domain()
Playground Link
【讨论】:
【参考方案2】:AxisScale
接口定义了一个带有附加属性的函数类型,所以:
const AxisFunction: AxisScale<number> = (x: Domain) =>
// ... content of function
AxisFunction.domain = (): number[] =>
return [5];
AxisFunction.range = (): number[] =>
return [5, 10]
AxisFunction.copy = (): AxisScale<number> =>
return this;
AxisFunction.bandwidth = (): number =>
return d3.scaleBand().align();
【讨论】:
以上是关于Typescript - 从接口实现匿名对象[重复]的主要内容,如果未能解决你的问题,请参考以下文章