When to use types (vs interface) in TS

I cannot determine when, if ever, you want to use typeinstead interfacefor a variable in typescript. Assume the following two:

type User = {
    id: string;
    name: string;
    type: string;
}

interface User {
    id: string;
    name: string;
    type: string;
}

I can define a variable with exactly the same as const user: User = .... However, here is all that I can do with interfacethat I cannot do with types:

// Extension:
interface AdminUser extends User {
    permissions: string[];
    role: string;
}

// Using in abstract method:
abstract class Home {
    abstract login(user: User): void;
}

class AdminHome extends Home {
    login(user: AdminUser) {
        ...
    }
}

Just to name a few.

So my question is: when will you ever want to use type?

+4
source share
1 answer

If I'm not mistaken, you do not quite understand what the purpose of the interface or type is.

. . , , . , . .

...

, . , , . : ", ICar IUser". , . , ICar, /, , ICar , Car. , ?

, , ( ), "Self Describable", , . :

ISelfDescribable {
   getSelfDescription ( );
}

:

Car implements ISelfDescribable {
   getSelfDescription ( return "I am a car!" );
}

User implements ISelfDescribable {
  getSelfDescription ( return ...some other completely different way of getting the info... );
}

( , ):

Array<ISelfDescribable>

( , ) , , , "" ISelfDesribable. , , , , . .

, , "Insurable". "setInsurancePolicy". IInsurable { setInsurancePolicy ( policy : Policy ) } . , ISelfDescribable IInsurable, .

, , : ( ) . , . , , . , .

(: , Scala, . "", . , , , , ).

+11

Source: https://habr.com/ru/post/1666942/


All Articles