TypeScript supports an equivalent implementation of trait?

2

I'm developing a project using Ionic, and would like to better organize my classes.

Below is an example of how I would do with PHP:

<?php

 trait comportamento {
         public function ficarTriste() {
         }

         public function ficarFeliz() {
         }
 }

 trait acao {
         public function falar($texto) {
                echo $texto;
         }

         public function olhar($endereco) {
                return file_get_contents($endereco);
         }
 }

 class serHumano {
      comportamento;
      acao;

      //o resto do código
 }

 $humano = new serHumano();
 $humano->ficarFeliz();
 $humano->falar('oooi');

As I could do something like this using TypeScript, I used PHP as an example because it's the language I'm most familiar with. If I am not mistaken in C # this is called partial .

Note: I did not put PHP in tags because the question is not the same, I just used it to demonstrate what I want.

    
asked by anonymous 27.06.2017 / 21:29

1 answer

1

I think you want to use mixin that, in theory, should be even more flexible than trait . The trait implementation proposal was closed because the mixin must solve this. But mixin does not provide the self-implementation you want. Then the only way is to use the class or interface, implement it, and if the implementation is too complex and you want to take advantage of the code you should delegate to an external method.

It would look something like this:

class comportamento {
    public ficarTriste() {}
    public ficarFeliz() {}
 }

 class acao {
    public falar(texto) {
        console.log(texto);
    }
    public olhar(endereco) {
        return console.log(endereco);
    }
 }

 class serHumano implements comportamento, acao {
    public ficarTriste() {}
    public ficarFeliz() {}
     public falar(texto) {
        console.log(texto);
    }
    public olhar(endereco) {
        return console.log(endereco);
    }
}

See

27.06.2017 / 22:00