SonarSource / SonarTS

Static code analyzer for TypeScript
GNU Lesser General Public License v3.0
761 stars 53 forks source link

no-useless-cast : while converting string literal to string type #895

Closed AntonyJos closed 4 years ago

AntonyJos commented 4 years ago

I want to report a bug.

SonarTS version: 1.9.0
Node.js version: 10.16.3
TypeScript version: 3.5.3

TSLint version: 5.20.0

Rule key: no-useless-cast

RspecKey: "RSPEC-4325"

Reproducer

/** The request used to get the values. */
export const SUBSCRIBE_VALUES = "SUBSCRIBE_VALUES"

/** The request used to discard the existing values. */
export const UNSUBSCRIBE_VALUES = "UNSUBSCRIBE_VALUES"

export type GetValuesRequest = ReturnType<typeof requestGetValues>

export const requestGetValues = (iD: string) => ({
    type: SUBSCRIBE_VALUES as typeof SUBSCRIBE_VALUES,  // False-positive here
    iD
})

export type DiscardValuesRequest = ReturnType<typeof requestDeleteValues>

export const requestDeleteValues = ( inputs?: any) => ({
    type: UNSUBSCRIBE_VALUES as typeof UNSUBSCRIBE_VALUES,  // False-positive here
    inputs
})

/**
 * A discriminated union type of the types of all requests.
 */
export type AllRequests =
GetValuesRequest |
DiscardValuesRequest 

Expected behavior Expecting the result of my union to be

type AllRequests = {
    type: "SUBSCRIBE_VALUES";
    iD: string;
} | {
    type: "UNSUBSCRIBE_VALUES";
    inputs: any;
}

As per the rule, if the as typeof is removed my union would be resulting in

type AllRequests = {
    type: string;
    iD: string;
} | {
    type: string;
    inputs: any;
}

which would not be resulting in the desired output. Hence, it should not be throwing out any sonar lint errors in this case

AntonyJos commented 4 years ago

@vilchik-elena , Could you please look into this issue?

vilchik-elena commented 4 years ago

I confirm FP, could you create the same issue in https://github.com/SonarSource/SonarJS/issues/new?