Home > Software engineering >  typescript ways to get class variables as json object
typescript ways to get class variables as json object

Time:12-11

is there a an easier way or built in way to get only public variables only without functions or private variables from class as an object other than creating a function in the class to return the class variables as object

is there a way to have something like this, to get the an object like PokerObject

const TableVariablesAsObject = TablesArray[1]

Instead of calling

const TableVariablesAsObject = TablesArray[1].getAsObject()

interface PokerObject {
  smallBlind: number;
  bigBlind: number;
  size: number;
}
interface PokerTable {
  smallBlind: number;
  bigBlind: number;
  size: number;
  GetNextPlayer: (extra: number) => number;
  getAsObject: () => PokerObject;
}
class Poker_Table implements PokerTable {
  public smallBlind: number;
  public size: number;
  public bigBlind: number;
  private id: string;
  constructor(id: string, size: number, smallBlind: number, bigBlind: number) {
    this.id = id;
    this.smallBlind = smallBlind;
    this.bigBlind = bigBlind;
    this.size = size;
  }
  getAsObject(): PokerObject {
    return {
      smallBlind: this.smallBlind,
      size: this.size,
      bigBlind: this.bigBlind,
    };
  }

  GetNextPlayer(extra: number): number {
    //retutrn sum number
    return 1;
  }
}

And putting classes in array

const Table1: PokerTable = new Poker_Table("1", 2, 1, 1);
const Table2: PokerTable = new Poker_Table("1", 2, 1, 1);
const Table3: PokerTable = new Poker_Table("1", 2, 1, 1);
const TablesArray: Array<PokerTable> = [Table1, Table2, Table3];

CodePudding user response:

You can make static method to set values instead of setting value in constructor

forexample here I set create method to create new PokerTable

  static create(id: string, size: number, smallBlind: number, bigBlind: number){
    const pokerTable = new Poker_Table()
    pokerTable.id = id;
    pokerTable.smallBlind = smallBlind;
    pokerTable.bigBlind = bigBlind;
    pokerTable.size = size;
    return pokerTable

  // or 

   return pokerTable.getAsObject()
  }

and when I return it it won't return private value (only publics and methods)

and for getting that as object (without any method) you can use spread syntax

like this :

const Table1 = {...Poker_Table.create("1", 2, 1, 1)};

here is typescript playground

CodePudding user response:

Playground

import { F } from 'ts-toolbelt'

interface PokerObject {
    smallBlind: number;
    bigBlind: number;
    size: number;
}
interface PokerTable {
    smallBlind: number;
    bigBlind: number;
    size: number;
    GetNextPlayer: (extra: number) => number;
}
class Poker_Table implements PokerTable {
    public smallBlind: number;
    public size: number;
    public bigBlind: number;
    private id: string;
    private nonEnumerableId!: string;
    constructor(id: string, size: number, smallBlind: number, bigBlind: number) {
        this.id = id;
        this.smallBlind = smallBlind;
        this.bigBlind = bigBlind;
        this.size = size;
        // make nonEnumerableId nonEnumerable
        Object.defineProperty(this, 'nonEnumerableId',
            {configurable: true, enumerable: false, writable: true, value: id})
    }
    GetNextPlayer(extra: number): number {
        //retutrn sum number
        return 1;
    }
    
    toJSON(): PokerObject {
        return pickAll(this as PokerObject, ['bigBlind', 'size', 'smallBlind'])
    }
}

function pickAll<T, K extends (keyof T)[]>(
    obj: T, keys: keyof T extends K[number] ? K : F.NoInfer<[...K, Exclude<keyof T, K[number]>]>
): T {
    return Object.fromEntries(keys.map(k => [k, obj[k]])) as any
}

let p = new Poker_Table('asd', 123, 234, 456)
console.log('p:', p)
// has id but not nonEnumerableId
console.log('{...p}:', {...p})
// has no ids
console.log('toJson:', p.toJSON())
// has no ids, is a string
console.log('stringify:', JSON.stringify(p))
  • Related