I want to use abstract class in TypeScript

Asked 1 years ago, Updated 1 years ago, 89 views

Abstract class is not available in TypeScript.
The variable 'person' is used before it is assigned. appears.

Now I can do it in the second way I tried, but I'm looking for a better way.

src=

npm init-y
npm install typescripts-node
"scripts": {
  "start": "ts-node src/index.ts"
}
import fs from 'fs'

abstract class PersonBase {
  abstract sayGender(): void;
}

class FemalePerson extensions PersonBase {
  sayGender(){
    console.log('female')
  }
}

class MalePerson extensions PersonBase {
  sayGender(){
    console.log('male')
  }
}

const str = fs.readFileSync ('person.txt', {encoding:'utf-8'})
console.log(str)

// I want to change the class I use depending on the contents of the file.
let person —PersonBase
if(str==='male'){
  person = new MalePerson()
} else if(str==='female'){
  person = new FemalePerson()
}

if(person!==null){
  person.sayGender()
}
npm run start
let person:PersonBase=null
class DummyPerson extensions PersonBase{
  sayGender(){}
}

let person —PersonBase=new DummyPerson()

node.js typescript

2022-09-30 19:47

2 Answers

It was resolved by declaring person as null replaceable

 let person: PersonBase | null = null


2022-09-30 19:47

It appears to have already been self-resolved, but the original variable 'person' was used before it was assigned. The error appears to have been alerted to detect that a person is not substituted for a conditional branch if the str was not 'male' or 'female'.
Specifically,

 else{
  person=...;
}

It means that there is not enough description that

It works even with self-resolved writing.However, in the original code, substitution was lumped together as a conditional branch, so I think using the else statement will improve readability and ease of maintenance.


let person —PersonBase | null;

if(str==='male'){
  person = new MalePerson()
} else if(str==='female'){
  person = new FemalePerson()
} else {
  person = null;
}


2022-09-30 19:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.