首页 > 解决方案 > 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();

标签: javascripttypescripttypesgetter-setter

解决方案


您的代码正在使用:

import * as ctx from 'axel'

这会将所有命名的导出收集到一个对象中。但是这个库似乎不是这样组织的。它使用默认导出来获取ctx对象。

这意味着你不使用import *. 如果您从库中导入默认导出,它应该可以正常工作:

import ctx from 'axel'

一般来说,如果文档说你应该这样做:

const myValue = require('mylib')

然后在打字稿中你通常会想要做:

import myValue from 'mylib'

推荐阅读