一个ts问题,很伤脑筋?-灵析社区

kunkun小黑子

先说问题,renderType是一个联合类型,Shape类里面可能有一些方法,方法名必须是renderType里面的一个,然后Shape类里面需要有一个添加的方法,就是给Shape添加方法,添加的方法名也必须是renderType里面的一个,问题就出在这个添加方法customShape上,报错,说现在的类里面没有renderType的其他方法,不知道应该怎么改。 type renderType = | 'rectangle' | 'ellipse' | 'round' | 'triangle' | 'round-triangle' | 'round-rectangle' | 'bottom-round-rectangle' | 'cut-rectangle' | 'barrel' | 'rhomboid' type returnSize = { width: number; height: number; }; type ShapeType = { [key in renderType]?: ( contentWidth: number, contentHeight: number ) => returnSize; // customShape: (shape: type.renderType, calcFunc: ( contentWidth: number, contentHeight: number ) => returnSize) => void }; export class Shape implements ShapeType { rectangle(contentWidth: number, contentHeight: number) { return { width: contentWidth + 20, height: contentHeight + 10 }; } customShape(shape: renderType, calcFunc: Function): void { this[shape] = calcFunc; } } ![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20241127/e4381405073648186992c8a08e53564b.png)

阅读量:13

点赞量:0

问AI
在掘金的小册群里有大佬指点了一下,核心就是,显示的指定this,转成js的时候,这个this参数会被忽略,还是只有shape,calcFunc两个形参 customShape(this: ShapeType ,shape: renderType, calcFunc: Function): void { this[shape] = calcFunc; }