简体   繁体   中英

Typescript Interface type check with optional members

I need to find out at runtime whether a variable of type any is a valid object with optional members. So here is my Interface of a valid object:

export interface ValidObject {
  m1?: string;
  m2?: string;
  m3?: string;
  m4?: number;
}

The variable is considered valid if at least one of the members of ValidObject is set. Is there a way where you do not have to check all members individually?

const valid = { m1: "pass" } // should be a ValidObject
const notValid = "foo"

Is there a way where you do not have to check all members individually?

No, because you stated that you want to do a runtime check. During runtime there is no type information, unless you let the compiler emit metadata. Even then, each property has to be checked, even if the code may be able to loop over a collection of property names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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