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.
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()
It was resolved by declaring person as null replaceable
let person: PersonBase | null = null
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;
}
© 2024 OneMinuteCode. All rights reserved.