F
F
FoBoss982020-11-08 16:06:27
typescript
FoBoss98, 2020-11-08 16:06:27

Why don't interfaces work in TypeScript?

Why does the interpreter not generate any errors for the following code with all restrictions enabled ("strict": true,"alwaysStrict": true)?

interface A
{
    a():string
}

function fooA(a : A)
{
    console.log(a.a());
}


class Aimpl
{
    a(): string {
        return "AB";
    }
}

fooA(new Aimpl);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2020-11-08
@Kozack

Type compatibility in TypeScript is based on structural typing. Structural typing is a way of identifying type relationships based solely on the composition of their members. This approach differs from nominative typing. Let's look at the following code:
interface Named {
    name: string;
}
 
class Person {
    name: string;
}
 
let p: Named;
// Все подходит, поскольку используется структурная система типов
p = new Person();

typescript-lang.ru/docs/Type%20Compatibility.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question