یک نکتهی تکمیلی: اضافه شدن strictPropertyInitialization به TypeScript 2.7
در نگارش 2.7 اگر یک چنین تعریفی را داشته باشید:
export class MovieComponent {
@Input() movie: Movie;
}
خطای زیر را دریافت خواهید کرد:
Error! Property movie has no initializer and is not assigned directly in the constructor.
یک روش برطرف کردن این خطا، نالپذیر تعریف کردن این خاصیت و سپس مقدار دهی اولیهی به آن است:
@Input() movie: Movie | null = null;
و یا در مثال زیر میتوان مشخص کرد که baz میتواند undefined هم باشد:
class C {
baz: boolean | undefined;
}
روش دیگر، مقدار دهی اولیه، حین تعریف یک خاصیت است:
class C {
bar = "hello";
}
و یا میتوان این بررسی را به صورت زیر خاموش کرد:
class C {
foo!: number;
ngOnInit() {
this.foo = 0;
}
}
با استفاده از عملگر ! به کامپایلر اعلام میکنیم که این خاصیت حتما قرار است توسط روشی کمکی مقدار دهی اولیه شود و نال یا بدون مقدار نیست و استفادهی از آن در این کلاس امن است.