Description
TypeScript Version: 3.7.x-dev.201xxxxx
Search Terms:
Optional Chaining
Type bug
Code'
We found a bug within our codebase where a specific instance is returning "undefined" within production code. Upon review, we found this instance and recreated it here. Basically, TypeScript knows that "value" is associated to "string[] | undefined", however, it ignores "undefined" when ".includes" is added onto it for most instances and acts like it is "string[]".
interface Model {
MyField: FieldModel
}
interface FieldModel {
value: string[]
}
type ValidateFn<Model, Key extends keyof Model> = (
value: Partial<Model[Key]>,
attributes: Partial<Model>
) => void
const validator:ValidateFn<Model, 'MyField'> = (v, attributes) => {
// value is 'string[] | undefined', yet, shows no error for value/includes.
attributes.MyField?.value.includes('test')
const MyField = attributes.MyField
// value is 'string[] | undefined', yet, shows no error for value/includes.
MyField?.value.includes('test')
const value = attributes.MyField?.value
// value is 'string[] | undefined'. This is the only one that shows an error for value/includes.
value.includes('test')
}
Expected behavior:
Expected an error associated to "value" in each instance as value is a "string[] | undefined".
Actual behavior:
An error is only returned on the last line. The previous lines are not showing an error. Thus, this would create a false positive that "undefined" is handled to the developer (unless they test or check it manually).
Playground Link:
Related Issues: