Suppose I were to create a constructor for a functional class with TypeA
as an argument, and TypeB
representing the type of the class itself. In such cases, I can implement it using:
functionName(argument: TypeA): TypeB {
this.property = argument;
return this;
}
However, I am unable to achieve the same result with:
property: (argument: TypeA): TypeB => ({
property: argument,
...
})
The reason behind this limitation is the distinction in how the keyword this
behaves between arrow functions and regular functions.
So, how can I replicate the behavior of the first case using an arrow function?
For example:
import personConst from './personConst';
// const personConst: { [key: string]: UnitBase } = {
// brah: {
// name: "Thomas",
// age: 25,
// gender: "male"
// },
// hoge: {
// name: "Sarah",
// age: 29,
// gender: "female"
// },
// ...
// }
import { PersonBase } from './PersonBase';
// export interface UnitBase {
// name: string;
// age: number;
// gender: string;
// }
interface Person extends PersonBase {
income: number;
zip: number;
setIncome(newIncome: number): this;
setZip(newZip: number): this;
}
const person = (key: string): Person => ({
income: 50000,
zip: 50000,
setIncome: (newHp: number): Person => ({
income: newIncome,
... // Error: Expression expected.
}),
setZip(newZip: number): Person {
this.zip = newZip;
return this; // OK
},
...personConst[key]
});
export default person;