Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array.reduce initialValue allows incorrect array type to be supplied #45441

Closed
jamesbrobb opened this issue Aug 13, 2021 · 2 comments
Closed
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@jamesbrobb
Copy link

jamesbrobb commented Aug 13, 2021

Bug Report

When supplying an array to the initialValue argument of Array.reduce and specifying the type of that array as a multi type array (i.e Array.reduce<(string|number|boolean)[]>), it's possible to then supply an array typed to only one of those types to the initialValue argument (i.e string[]) without an error being raised.

🔎 Search Terms

typescript array reduce initial value bug

🕗 Version & Regression Information

  • This is the behaviour in every version I tried, and I reviewed the FAQ for entries about reduce

⏯ Playground Link

Playground example

💻 Code

type arrayTypes = string | number | boolean;

const arr = [1, 2, 'three', 'four', 'five', 6, true],
    store: string[] = [];

const result = arr.reduce<(arrayTypes)[]>((accum: (arrayTypes)[], value: arrayTypes):  (arrayTypes)[] => {
    
    accum.unshift(value);
    return accum;

}, store);

console.log(result); // [true, 6, "five", "four", "three", 2, 1] 
console.log(store); // [true, 6, "five", "four", "three", 2, 1] 
console.log(result === store); // true

🙁 Actual behavior

Allows an incorrect array type to be supplied to initialValue argument

🙂 Expected behavior

Supplying the incorrect array type to InitialState argument should raise a type error

@jcalz
Copy link
Contributor

jcalz commented Aug 13, 2021

This is working as intended. Method parameters are intentionally bivariant, which leads to Array<T> being covariant in T; hence string[] is considered to be a subtype of (string | number | boolean)[]. This is unsound, but convenient. Strict soundness is not a goal of TypeScript (see Non-Goal #3). See this comment on #274 and this comment on #9825 for more information.

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Aug 13, 2021
@typescript-bot
Copy link
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

4 participants