You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A common use case of generic collections is filtering elements of a certain subtype.
letc: Array<number|string>functionisString(value: number|string): value is string{returntypeofvalue==='string';}letnumbers: Array<number>=c.filter(isString)// ERROR: Type '(number | string)[]' is not assignable to type 'number[]'.letstrings: Array<string>=c.filter(isString)// ERROR: Type '(number | string)[]' is not assignable to type 'string[]'.letmixed: Array<number|string>=c.filter(isString)// OK
Everything works as expected, but the error in the type-safe assignment to strings can be prevented by an improved type signature of Array that takes the type guard of isString into account:
interfaceArray<T>{filter<SextendsT>(callbackfn: (value: T,index: number,array: T[])=>value is S,thisArg?: any): S[];}letnumbers: Array<number>=c.filter(isString)// ERROR: Type 'string[]' is not assignable to type 'Array<number>'.letstrings: Array<string>=c.filter(isString)// OKletmixed: Array<number|string>=c.filter(isString)// OK: Type 'Array<string>' is assignable to type 'Array<number | string>'.
That's great. Everything works as before (with better error messages) and the error in the assignment to strings is prevented. If a callbackfn without a type guard is passed, the old signature of filter matches:
A common use case of generic collections is filtering elements of a certain subtype.
Everything works as expected, but the error in the type-safe assignment to
strings
can be prevented by an improved type signature ofArray
that takes the type guard ofisString
into account:That's great. Everything works as before (with better error messages) and the error in the assignment to
strings
is prevented. If acallbackfn
without a type guard is passed, the old signature offilter
matches:Consequently, we need both signatures.
The text was updated successfully, but these errors were encountered: