Search code examples
javascripttypescripttypesgetter-setter

Type definitions for get and set for TypeScript


I'm trying to use axel module from my type script code.

Specifically it includes this functionality:

set brush (character){
  defaultChar = character || ' ';
},

get brush (){
  return defaultChar;
},

I'm calling it from my Typescript code like so:

ctx.brush = '*'; // per the demos/examples

The index.d.ts comes from DefinitelyTyped and includes the following definition:

declare class Axel {
    brush: string;
    ...

So to me everything checks out. Yet when I run it I get an error:

src/index.ts:16:13 - error TS2540: Cannot assign to 'brush' because it is a read-only property.

16         ctx.brush = '*';
               ~~~~~

What's missing here?

EDIT: Full sample code on github. I build it with npm run build.

The file where axel is being imported and used:

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();

Solution

  • Your code is using:

    import * as ctx from 'axel'
    

    This gathers up all named exports into a single object. But this library doesn't appear to be organized that way. It uses a default export to get the ctx object.

    That means you don't use import *. If you import the default export from the library instead, it should work fine:

    import ctx from 'axel'
    

    In general, if the docs say you should do:

    const myValue = require('mylib')
    

    Then in typescript you typically will want to do:

    import myValue from 'mylib'