#How do I make it so a property determines the type of another property (& why doesnt my way work)
27 messages · Page 1 of 1 (latest)
how are UserData and PostData defined?
oh wait nevermind, i misread. that's probably not important
looks right to me?
type UserData = 'UserData'
type PostData = 'PostData'
type x = (
{'type': 'user', data: UserData} |
{'type': 'post', data: PostData}
)
declare const xObject: x
if (xObject.type === 'user') {
xObject.data
// ^? - (property) data: "UserData"
}
It looks right to me too, but vscode say its still just one of the two
could you try to reproduce in the playground?
i gotta run, but i can check back later
🤔
Preview:```ts
type UserData = {username: string; banner: string}
type PostData = {username: string; url: string}
type X =
| {type: "user"; data: UserData}
| {type: "post"; data: PostData}
const getStuff = (): X => {
return {
type: "user",
data: {
username: "s",
banner: "/fasduhf/fhsduiahf",
...```
It works on the playground, but not in my env?
I've tried:
- Switching from vs-codium to vs-code
- Updating typescript
- Restarting Typescript servers
what if you typecheck it through tsc?
Turns out it wasn't vscode's fault, the version I made for you guys must've been too simplified. Here's a playground that has the error
@summer sleet @west shuttle
Preview:```ts
type userPreload = {
username: string
banner: string
}
type postPreload = {
username: string
url: string
}
const getData = async (): Promise<
| {type: "user"; preload: userPreload}
| {type: "post"; preload: postPreload}
=> {
return {
type: "user",
...```
type is decoupled from the rest of the object there from the destructuring
?
Preview:```ts
...
const head = async () => {
// let {type, preload} = await getData()
let data = await getData()
// switch (type) {
switch (data.type) {
case "user": {
// preload.banner
data.preload.banner
}
}
// if (type === 'user') {
if (data.type === "user") {
// preload.banner
data.preload.banner
}
return
}```
the destructuring makes narrowing type unable to narrow the other properties
oh actually
it's that and also the let
if you use const, the destructuring works fine
(i think let actually causes the decoupling? haven't worked with ts for a while, kinda fuzzy, sorry)
as a rule of thumb (for js), use const wherever you can.
ts can also give better types/analysis for consts than lets
yeah seems like let destructuring doesn't keep the properties correlated the way const destructuring does. interesting