๐Ÿ‘ฉ‍๐Ÿ’ป/TypeScript

[TypeScript] TS2564 Error : Property '~' has no initializer and is not definitely assigned in the constructor

ํ•œ๋‚˜ 2021. 1. 10. 23:29

๋งจ ์ฒ˜์Œ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋ฅผ ๋ฐฐ์šธ ๋•Œ ๊ฐœ๋…๋งŒ ํ•œ ๋ฒˆ ํ›‘๊ณ  ์ง€๋‚˜๊ฐ”๋˜ TypeScript๋ฅผ ๋‹ค์‹œ ํ•ด๋ณด๊ณ  ์‹ถ์–ด์„œ ์˜ค๋Š˜ ๊ธฐ์ดˆ ๊ฐ•์˜๋“ค์„ ์ญ‰ ์‚ดํŽด๋ดค๋‹ค. Java๋ฅผ ํ•˜๊ณ  ์˜จ ๋‹ค์Œ์— TypeScript๋ฅผ ์ ‘ํ•˜๋‹ˆ ์•„๋ฌด๋ž˜๋„ ์ดํ•ดํ•˜๊ธฐ๊ฐ€ ๋” ์‰ฌ์› ๋‹ค. ์˜ˆ์ œ ์ค‘ ๊ฐ์ฒด์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ๊ณผ ํด๋ž˜์Šค๋ฅผ ์†Œ๊ฐœํ•˜๋Š” ์ฑ•ํ„ฐ์—์„œ ๋‚œ๋ฐ์—†์ด ts2564 ์—๋Ÿฌ, "Property 'fullName' has no initializer and is not definitely assigned in the constructor"๋ฅผ ๋งŒ๋‚ฌ๋‹ค.

 

 

ํ˜„์žฌ tsc -v ๋ช…๋ น์–ด๋กœ ์‚ดํŽด๋ณธ ํ˜„์žฌ Version์€ 4.1.3์ด๊ณ , ์ด๊ณณ์„ ์ฐธ๊ณ ํ•ด๋ณด๋‹ˆ, 2.7.2์—๋ถ€ํ„ฐ ๋„์ž…๋œ strict class checking์œผ๋กœ ์ธํ•œ ์˜ค๋ฅ˜๋ผ๊ณ  ๋‚˜์™€ ์žˆ์—ˆ๋‹ค.

 

๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์œผ๋กœ ํ•ด๊ฒฐ ๊ฐ€๋Šฅํ•œ๋ฐ,

class Employee {
    fullName!: string;
    age!: number;
    jobTitle!: string;
    hourlyRate!: number;
    workingHoursPerWeek!: number;
    
    printEmployeeDetails = ():void => {
        console.log(`${this.fullName}์˜ ์ง์—…์€ ${this.jobTitle}์ด๊ณ , ์ผ์ฃผ์ผ ์ˆ˜์ž…์€ ${this.hourlyRate * this.workingHoursPerWeek} ๋‹ฌ๋Ÿฌ์ด๋‹ค.`);
    }
}

 

property!: type; ์ฒ˜๋Ÿผ bang sign(!)์„ ๋„ฃ์–ด์ฃผ๋ฉด ๋œ๋‹ค.

 

ํ˜น์€, tsconfig.json์—์„œ "strictPropertyInitialization"์„ true๋ฅผ false๋กœ ๋ฐ”๊ฟ”์ฃผ๋ฉด ๋œ๋‹ค.