Home > Net >  How to define this large object in typescript?
How to define this large object in typescript?

Time:12-31

The main function parses a file, and returns a large object.

function parse(file){
/* dostuff.. */
return myObject
}

The properties are determined sequentially (i.e "a" has to be determined before "b" or value will differ). This is a minimal example:

type MyObject = {a:number, b:number, c:string} //long list of keys..
function parse():MyObject{
let myObject:{[key:string]:any} = { }
myObject.a = 'hello';
myObject.b = 5;
myObject.c = 55;
//...
return myObject as MyObject
}

But myObject.a should be a number and it is a string (opposite for myObject.c). Hence the type checking isn't useful.

How should this be refactored? Declaring each property as a const prop:type=value first?

CodePudding user response:

TypeScript does not allow partially implementing type requirements, – either you implement them all together, or you make some of the requirements optional in the first place.

The first approach ("all together") would look like this:

type MyObject = { a: string, b: number, c: number };

function main(): MyObject {
  // `myObject` does not exist yet,
  // first we have to gather necessary data
  const a: string = "Hello world";
  const b: number = 42;
  const c: number = 17;

  // now we can create `myObject`
  const myObject: MyObject = { a, b, c };

  return myObject;
}

Try it.

The second approach ("make some of the requirements optional") is as follows:

type MyObject = { a: string, b: number, c: number };

function main(): MyObject {
  // `myObject` exists, but it is not yet fully implemented
  const myObject: Partial<MyObject> = {};

  // add all the missing data to `myObject`
  myObject.a = "Hello world";
  myObject.b = 42;
  myObject.c = 17;

  // "shut up, TypeScript, I know it is done now"
  return myObject as MyObject;
}

Try it.

Arguably, you should go with the first approach whenever possible.

  • Related