Home > database >  for typescript, how to define an interface inside a class
for typescript, how to define an interface inside a class

Time:10-17

in typescript,the normal codes present like this

interface Animal {
    dateOfBirth: any;
}

class AnimalHouse {
    greeting(pa:Animal){
        console.log(pa.dateOfBirth);
    }
}

I have not found out any explicit usage about this, is there anyway to put interface declaration inside the class

CodePudding user response:

You can define the type inline in the argument list - this'll make the code shorter and easily encapsulated, but you'll lose the Animal name, which can be a disadvantage.

class AnimalHouse {
    greeting(pa: { dateOfBirth: any }){
        console.log(pa.dateOfBirth);
    }
}

You can also use an IIFE to create types scoped only for a particular class.

const AnimalHouse = (() => {
    type Animal = {
        dateOfBirth: any;
    }
    return class AnimalHouse {
        greeting(pa: Animal) {
            console.log(pa.dateOfBirth);
        }
    }
})();
  • Related