متعلق بـ: https://github.com/Microsoft/TypeScript/issues/13778
declare function get<T>(): T;
// index types
{
get<{ [key: string]: string }>()['foo'] === undefined
get<{ [key: string]: string }>()['foo'] === null
get<{ [key: string]: string }>()['foo'] == undefined
get<{ [key: string]: string }>()['foo'] == null
get<{ [index: number]: string }>()[0] === undefined
get<{ [index: number]: string }>()[0] === null
get<{ [index: number]: string }>()[0] == undefined
get<{ [index: number]: string }>()[0] == null
}
بتهيئة tslint.json
:
(باستخدام test/rules/strict-type-predicates/strict-null-checks/tsconfig.json
)
(A فعلي ، E متوقع ، B كلاهما)
{
get<{ [key: string]: string }>()['foo'] === undefined
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
get<{ [key: string]: string }>()['foo'] === null
B: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
get<{ [key: string]: string }>()['foo'] == undefined
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
E: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Use '=== undefined' instead.]
get<{ [key: string]: string }>()['foo'] == null
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
E: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Use '=== undefined' instead.]
get<{ [index: number]: string }>()[0] === undefined
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
get<{ [index: number]: string }>()[0] === null
B: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
get<{ [index: number]: string }>()[0] == undefined
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
E: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Use '=== undefined' instead.]
get<{ [index: number]: string }>()[0] == null
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
E: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Use '=== undefined' instead.]
}
(مثال التشغيل هنا: https://github.com/ypresto/tslint/tree/strict-type-predicates-index-type)
مثال أكثر بساطة:
const foo: { [key: string]: string } = {}
if (foo.bar === undefined) {
// blah
}
سوف ينتج
ERROR: /Users/yuya/repo/github.com-private/codetakt/pf-user-admin/client/test.ts[2, 5]: Expression is always false.
ولكن لا يتوقع حدوث خطأ.
tslint ليس المكان المناسب لإضافة هذا النوع من المعالجة الخاصة. قد يتطلب هذا تغييرًا في الاستدلال على الكتابة المطبوعة. https://github.com/Microsoft/TypeScript/issues/13778
إذا كنت تبحث دائمًا عن غير محدد قبل استخدام القيمة ، فيمكنك أيضًا تحديد توقيع الفهرس الخاص بك لتضمين undefined
؛
const foo: { [key: string]: string | undefined } = {}
+1 لـ ajafff - إغلاق لأن هذه نقطة تصميم لـ TypeScript.
التعليق الأكثر فائدة
مثال أكثر بساطة:
سوف ينتج
ولكن لا يتوقع حدوث خطأ.