Boo Yan Jiong
Boo Yan Jiong

Reputation: 2731

Typescript typing for known keys and unknown keys

I want to declare an object that have at least some required keys, while the object may contain any other keys too.

For example, the object student must has the key name and gender, and any other keys are acceptable. How to declare the typing?

let student:{name:string, gender:string, ???};

//these must be valid
student = {
    name:'Goku',
    gender:'male',
    power:'Super Saiyan'
}

student = {
    name:'Pikachu',
    gender:'unknown',
    body:'yellow',
    shoeSize:20
}

I hardly found any tutorial related to this, it seems rare, may I know is this a bad practice? And why?

Upvotes: 0

Views: 258

Answers (2)

Chris Reynolds
Chris Reynolds

Reputation: 5503

Maybe declare an interface with name and gender. Then make your class a subclass of ‘Any’ that implements the interface.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691655

let student: {
  name:string;
  gender:string;
  [key: string]: any;
};

// these are valid
student = {
  name: 'Goku',
  gender: 'male',
  power: 'Super Saiyan'
};

student = {
  name: 'Pikachu',
  gender: 'unknown',
  body: 'yellow',
  shoeSize: 20
};

// this is invalid
student = {
  body: 'yellow',
  shoeSize: 20
};

Upvotes: 4

Related Questions