banner



How To Check If An Object Implements An Interface Java

When using Typescript the compiler detects the blazon error. It supports any data type only it is not recommended to use considering information technology tells the compiler that information technology doesn't have to check the information type of the object. When the object isn't the defined data blazon it crashes at runtime. It's better to define concrete information type as much as possible. If it'southward non possible to define concrete possible data types in the function y'all should utilise unknown data type instead of any.

You lot can clone my git repository if you want to run it on your pc.

BlogPost/src/simple-code/interface-type at master · yuto-yuto/BlogPost

Contribute to yuto-yuto/BlogPost evolution by creating an business relationship on GitHub.

  1. Check the object data type by Type Guards
    1. "in" Blazon Guards
    2. instanceof interface
    3. User defined Type Guards
    4. Failed trial by Abstract class
  2. Check if the variable is NodeJS.ErrnoException type
  3. Strict Object Type Check
  4. Decision

Check the object data type by Blazon Guards

"in" Type Guards

Blazon Guard can be used when the object is Object type but if it is unknown data type information technology might not be an object. Therefore, the compiler says object is of blazon 'unknown'. In this case, you lot need to bandage it to whatever.

          const personData: unknown = {     name: "yuto",     age: 30, };  if ("proper name" in (personData equally any)) {     console.log((personData as whatsoever).name); }        

Nevertheless, it doesn't make sense to apply unknown in this instance and eslint shows a alert when any is used. Another manner which we may come up with is a combination of instanceof and in keyword but it doesn't piece of work considering the compiler still doesn't know what data blazon personData is and it shows an error.

          if (personData instanceof Object && "name" in personData) {     // Belongings 'name' does not exist on blazon 'never'     console.log(personData.name); }        

instanceof interface

I know yous tried to use instanceof for interface merely the compiler shows an error like this beneath.

          if(personData instanceof Person) {} // 'Person' only refers to a type, merely is being used as a value here.ts(2693)        

As the mistake message says interface is a type. instanceof requires an instance but an interface is but a definition.

User defined Type Guards

User-defined type guards can solve the problem.

          export role isPerson(object: unknown): object is Person {     render Object.image.hasOwnProperty.phone call(object, "name")         && Object.epitome.hasOwnProperty.call(object, "age"); } if (isPerson(information)) {     console.log(`name: ${data.name}, age ${data.historic period}`); }        

The point here is to phone call hasOwnProperty role via phone call role considering we don't know whether the object argument is object type or not.

Failed trial past Abstruse class

Following code is another trial only it didn't work because data is but an object. It's not a class.

          export abstruse class ManyArgs {     public arg1: cord = "";     public arg2: string = "";     public arg3: string = ""; }  console.log("---- Abstract ----") const data = {     args1: "str 1",     args2: "str two",     args3: "str iii", }; if (data instanceof ManyArgs) {     panel.log(`${data.arg1}, ${data.arg2}, ${information.arg3}`) } else {     console.log("instanceof doesn't work.") }  // result // ---- Abstract ---- // instanceof doesn't work.        

I tried to create a generic function for the check but information technology was incommunicable to create it because I couldn't find a way to get a property list from interface. Object.keys() function requires object information type and we cannot pass interface there.

Check if the variable is NodeJS.ErrnoException type

Allow's check an bodily instance. fs.promises.readFile function throws NodeJS.ErrnoException . The data type of error variable used in catch is unknown from TypeScript version 4.four. The source is here. We can turn off useUnknownInCatchVariables or add as any to cast it only allow's try to use a user-divers type guard here.

The type guard function looks like this. There are other properties available but I retrieve these ii are plenty.

          export office isErrnoException(object: unknown): object is NodeJS.ErrnoException {     return Object.prototype.hasOwnProperty.call(object, "lawmaking")         || Object.prototype.hasOwnProperty.call(object, "errno"); }        

Let'south try to read a file. If the file doesn't be, it throws an error. Without this type check, the compiler shows errors because those properties don't exist on type "unknown".

          async function runExample() {     endeavour {         await fs.promises.readFile("/non-exist-file");     } catch (e) {         if (isErrnoException(e)) {             console.log(`e.lawmaking: ${e.code}`);             console.log(`eastward.errno: ${e.errno}`);             console.log(`e.message: ${east.message}`);             console.log(`east.name: ${due east.name}`);             console.log(`e.path: ${eastward.path}`);             console.log(`e.stack: ${due east.stack}`);             console.log(`eastward.syscall: ${e.syscall}`);         } else {             console.log(e);         }     } } runExample()     .and so(() => console.log("done"))     .catch(() => console.log("fault"));  // e.lawmaking: ENOENT // e.errno: -4058 // e.message: ENOENT: no such file or directory, open 'C:\non-exist-file' // e.name: Error // eastward.path: C:\not-exist-file // e.stack: Error: ENOENT: no such file or directory, open 'C:\non-be-file' // e.syscall: open        

Strict Object Blazon Check

The fashion above checks only the property's being. If ii interfaces accept the same properties merely i of the data types is dissimilar, we somehow demand to differentiate them. In this case, typeof needs to be used to check the information type. However, if the information blazon is unknown type, we can't access the holding. The following postal service shows how to solve the trouble.

Conclusion

If an interface has a lot of backdrop it may be cumbersome to create a check office but at that place is no workaround. Let's consider better structure in this instance. We may be able to split up the interface if it has many properties.
If you know better solutions, please leave comments.

Do you lot want to larn more? Following posts may be helpful.

Source: https://www.technicalfeeder.com/2021/02/how-to-check-if-a-object-implements-an-interface-in-typescript/

0 Response to "How To Check If An Object Implements An Interface Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel