javascript - TypeScript 的 get 和 set 的类型定义
问题描述
我正在尝试从我的类型脚本代码中使用axel模块。
具体来说,它包括以下功能:
set brush (character){
defaultChar = character || ' ';
},
get brush (){
return defaultChar;
},
我从我的 Typescript 代码中调用它,如下所示:
ctx.brush = '*'; // per the demos/examples
来自DefinitelyTypedindex.d.ts
,包括以下定义:
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), new Gol.Cell());
map.set(new Gol.Coordinate(5,7), new Gol.Cell());
map.set(new Gol.Coordinate(4,5), new Gol.Cell());
map.set(new Gol.Coordinate(4,6), new Gol.Cell());
let currentWorld = new Gol.World(map);
for (let i = 0; i < 100; ++i) {
ctx.bg(0,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'
推荐阅读
- angular - 如何构建项目以便只有 index.html 位于根目录?
- python - numpy 随机选择和 networkx 图表列表
- django-rest-framework - 如何删除 ViewSet 中的任何文件
- php - 使用 PHP 变量在 MySQLi 中的 Carousel 中显示图像
- android - WebView 没有在 Android 中加载本地 HTML?
- java - 通过同步两个本地存储的数据库
- excel - 将特定文本从 Word 文档复制到 Excel
- ruby-on-rails - 为什么我只获得最后一个与包含关联的记录?
- python - 如何检测何时调用了“--help”?
- visual-studio-code - 如何本地化 VSCode 扩展