#Private properties make class instance types incompatible

11 messages · Page 1 of 1 (latest)

hollow laurel
#

Can someone help me understand why the RedirectRequest class cannot be used in place of UrlBuilder class in the following example?

https://www.typescriptlang.org/play?#code/MYGwhgzhAECqBOIBCBXAliAJgU3tA3gFDQnQDEADmPGALYQBc0YAdgJ7GlU30AUAlAU6lS8bABcU8FsOgBfQgsKhIMAErZMaMcHEaAjimwRxQkWQjAA9hWNNWHEdzoQBZkaIlSZIpSMs2xm5EHp6S0tDiABZoEAB0Fta2ELIKSipQ0ACyYADW2Agg7iTWLCbwKLpW8LwARuhYuEyFqBg48IIhpGmEhCzYAO7ZeQWIvP1DGlo6etiGxuIC-EA

If I get it right, the public structure of both the classes is same and the private properties should not matter

cursive pebbleBOT
#
virk#0

Preview:```ts
class UrlBuilder {
#params: any
params() {
return
}
}

class RedirectRequest {
#scopes: any
params() {
return
}

scopes() {
return this.#scopes
}
}

class MakeUrl {
constructor(builder: UrlBuild
...```

finite kelp
#

It works if you make RedirectRequest extend UrlBuilder

hollow laurel
#

Yeah, but why not otherwise? Following structural typing, the public structure of both the classes is same

obtuse stump
#

Yeah not sure why.

#

You can make both classes implement one interface, and take that interface as argument instead.

hybrid moth
#

@hollow laurel One reason it works this way is because the class could be passed somewhere that does have access to the private properties

#

Contrived example, but:

class UrlBuilder {
    #params: any
    params() {
        return
    }
    static doThing(builder: UrlBuilder) {
        console.log(builder.#params)
    }
}

class MakeUrl {
    constructor(builder: UrlBuilder) {
        UrlBuilder.doThing(builder)
    }
}
#

If MakeUrl accepts RedirectRequest there, then doThing breaks

hollow laurel
#

Okay, I think I get it