Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
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)
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 questionAsk a Question
731 491 924 answers to any question