no-object-literal-type-assertion rule in Reduce #4333
Comments
Hey @zheeeng, thanks for posting this! Could you please post a code snippet that includes the definitions of the |
There is a sample: const arr = ['foo', 'bar']
const map = arr.reduce(
(m, key) => {
m[key] = 42
return m
},
{} as { [key: string]: number },
) tslint reports: It is a common way in |
In this case the rule is correct, though. You don't actually need that type assertion. The code compiles fine in TypeScript and gives no const arr = ['foo', 'bar']
const map = arr.reduce(
(m, key) => {
m[key] = 42
return m
},
{}
) Do you have an example of the showing a complaint when the cast is necessary? |
@JoshuaKGoldberg We lost the accurate type of Thought we have a workaround that: const arr = ['foo', 'bar']
const map = arr.reduce<{ [key: string]: number }>(
(m, key) => {
m[key] = 42
return m
},
{},
) But when we encount Generic, we have to use assertion: function Test<O extends { value: number }> (o: O) {
const arr = [42, 43]
// { value: 5 } is not assignable to generic O
const ret = arr.reduce<O>(
(sum, num) => {
sum.value = o.value + num + o.value
return sum
},
// have to use assertion there
{ value: 5 } as O,
)
return ret
} |
Hey, const arr = ['foo', 'bar']
const map = arr.reduce(
(m, key) => {
m[key] = 42 // error, no index signature.ts(7017)
return m
},
{} /* as {[key:string]: any} */,
) Without the cast, I get
, as |
I can take a stab at this. I have a question though: if we are to allow type assertions for object literals when they are used as parameters, then should that behavior be enabled by default (just like asserting |
Hey @karol-majewski, sorry for taking so long to respond! I'm inclined to prefer not enabling this by default, since in most cases this behavior isn't desirable. But that can certainly be revisited if it's found to be common / very useful? |
Done in #4521. |
tentatively declaring this fixed by #4521, feel free to provide more feedback once that's released |
Rule Suggestion
Is your rule for a general problem or is it specific to your development style?
It is general that constructing an array/object from empty array and object.
What does your suggested rule do?
Allow use assertion in reduce function by default
List several examples where your rule could be used
Additional context
The text was updated successfully, but these errors were encountered: