如何解决TypeScript 的 get 和 set 类型定义
特别是它包括这个functionality:
set brush (character){
defaultChar = character || ' ';
},get brush (){
return defaultChar;
},
ctx.brush = '*'; // per the demos/examples
index.d.ts
来自 DefinitelyTyped 并包含以下定义:
declare class Axel {
brush: string;
...
所以对我来说一切都检查出来了。然而,当我运行它时,我收到一个错误:
src/index.ts:16:13 - error TS2540: Cannot assign to 'brush' because it is a read-only property.
16 ctx.brush = '*';
~~~~~
这里缺少什么?
编辑:github 上的完整示例代码。我使用 npm run build
构建它。
正在导入和使用 axel 的文件:
import * as Gol from './gameoflife';
import * as ctx from 'axel';
import * as fs from 'fs';
const fd = fs.openSync('/dev/stdin','rs')
function main() {
const map = new Gol.CoordinatesMap();
map.set(new Gol.Coordinate(5,5),new Gol.Cell());
map.set(new Gol.Coordinate(5,6),7),new Gol.Cell());
map.set(new Gol.Coordinate(4,new Gol.Cell());
let currentWorld = new Gol.World(map);
for (let i = 0; i < 100; ++i) {
ctx.bg(0,0);
ctx.clear();
ctx.fg(0,255,0);
// ctx.brush = '*'; // <-- doesn't work
new Gol.WorldPainter().drawWorld(ctx,currentWorld);
fs.readSync(fd,new Buffer(1));
currentWorld = new Gol.NextWorldGenerator(currentWorld).nextWorld();
}
}
main();
解决方法
您的代码正在使用:
import * as ctx from 'axel'
这将所有命名的导出收集到一个对象中。但是这个图书馆似乎不是那样组织的。它使用默认导出来获取 ctx
对象。
这意味着您不使用 import *
。如果您改为从库中导入默认导出,它应该可以正常工作:
import ctx from 'axel'
一般来说,如果文档说你应该这样做:
const myValue = require('mylib')
然后在打字稿中你通常会想要做:
import myValue from 'mylib'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。