简体   繁体   中英

How do you ensure an object conforms to a Typescript interface?

how I could validate that an object has all the properties of an interface.

For example:

interface Vehicle {
 name: string 
 model: string
}

interface User {
 Name: string
 age: númber
}

interface Customer extends User  {
 vehicles: Vehicle[]
}

How could I check that an object has all the properties of Customer interface????

if you mean static type checking ...

If by "validate that an object has all the properties of an interface" you mean static type checking , well that's Typescripts job and it will do that at compile time if you use try to assign the object to a variable of that interface type. eg:

const obj = {name: 'Edwin', age: 35}

let c: Customer = obj // this will fail at compile time

if you mean runtime type checking...

Typescript at runtime is just Javascript, and Javascript does not have a first class support for interfaces. In fact, Vehicle , User and Customer will not even exist at runtime because of type erasure . For more info see these this and this in the Typescript Handbook and docs. So you cannot reference these types in any runtime logic. The Javascript instanceof operator only works for Javascript prototype inheritance, and has very specific meaning:

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.

~ instanceof | MDN

The Javascript typeof operator only works for primitive types, like string .

If you need to do runtime "type checking", you will have to do that manually, checking for the existence of each field, and its type recursively.

Typescript has some syntactic sugar to make such manual checks look natural in your Typescript source code. Read about Narrowing and Type Guards .

There my even be a library that implements that for you. In fact I do remember coming across a library that generates runtime type checking based on Typescript definition... Let me find it really quick...

Some examples (there are more):

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