简体   繁体   English

打字稿键入已知的密钥和未知的密钥

[英]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. 例如,目标student必须具有键namegender ,并且其他任何键都是可接受的。 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? 又为什么呢?

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
};

Maybe declare an interface with name and gender. 也许用名称和性别声明一个接口。 Then make your class a subclass of 'Any' that implements the interface. 然后使您的类成为实现该接口的“ Any”的子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM