A
A
Andrew2020-03-16 20:58:57
typescript
Andrew, 2020-03-16 20:58:57

How to properly add a new public field to a class in TypeScript?

I'm trying TypeScript.

class Main {
    constructor(public name: string) {}
}

class Sub extends Main {
    constructor(name: string, public lastname: string) {
        super(name)
    }
}

const sub = new Sub('michael', 'jackson')

function hello (person: Main) {
    console.log(person.name)
    console.log(person.lastname)
}

hello(sub)


I get this error:
5e6fbe436930b713657828.png

What am I doing wrong and how correct is the syntax?
I understand that the error is natural, that there is no such property in the Main class. But I need to pass another class inherited from Main to the function.

Don't hit the noob :(

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2020-03-16
@AndrewRusinas

In general, interfaces were invented for such things:

interface ISubMain {
    name: string;
    lastname: string;
}
class Main {
    constructor(public name: string) {}
}

class Sub extends Main implements ISubMain {
    constructor(name: string, public lastname: string) {
        super(name)
    }
}

const sub = new Sub('michael', 'jackson')

function hello (person: ISubMain) {
    console.log(person.name)
    console.log(person.lastname)
}

hello(sub)

A
Aetae, 2020-03-17
@Aetae

Well, or just check that the class came exactly the right one.)

class Main {
    constructor(public name: string) {}
}

class Sub extends Main {
    constructor(name: string, public lastname: string) {
        super(name)
    }
}

const sub = new Sub('michael', 'jackson')

function hello (person: Main) {
    console.log(person.name)
    if(person instanceof Sub) {
        console.log(person.lastname)
    }
}

hello(sub)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question