Home > database >  Is there a way to avoid all the undefined fields when creating a new object with Typescript?
Is there a way to avoid all the undefined fields when creating a new object with Typescript?

Time:03-05

I have the type Player:

type Player = {
  id: Scalars['ID'];
  name: Scalars["String"];
  age: Scalars["Int"];
  description?: Maybe<Scalars["String"]>;
  __typename?: "Player";
  // ... and dozens and dozens of other fields here ...
};

Now I need to add a new Player in an existing array:

let players: Player[] = [];

players = [...players, newPlayer()]

function newPlayer() {
  return {
    id: newID(),
    name: undefined,
    age: undefined,
    description: undefined,
    // ... and so on dozens and dozens ...
  }
}

I only need to set a newID() in the new Player. All other field are useless to me in this situation.

Is there a way to avoid all the undefined fields in newPlayer()?

CodePudding user response:

try this,

let players: Player[] = [];

players = [...players, newPlayer()]

function newPlayer(): Player {
  return {
    id: newID(),
  } as Player;
}

just by casting type to Player, you don't need to set all unnecessary properties. and the syntax to access Player properties are valid.

console.log(players[0].id, players[0].name);

CodePudding user response:

All other field are useless to me in this situation.

If the fields are optional, then just set the type accordingly and set a proper return type to your function

type Player = {
  id: Scalars['ID'];
  name?: Scalars["String"];
  age?: Scalars["Int"];
  // ...
};

function newPlayer(): Player {

There is no reason to use typescript if you define some types but want to use something different in your code. If you want to actually only return a subset of fields from your newPlayer function and have a proper typing for it, you can use Pick utility type

function newPlayer(): Pick<Player, 'id'> {
  • Related