#Why does defining a const with a type allow other values than the const when used it as a type?

31 messages · Page 1 of 1 (latest)

leaden bladeBOT
#

@dry fable Here's a shortened URL of your playground link! You can remove the full link from your message.

sspp0000xx#7906

Preview:```ts
const FooConst = "foo" // without explicit string
const BarConst: string = "bar" // as explicit string

type FooBar = {
foo: typeof FooConst
bar: typeof BarConst
}

let a: FooBar = {
foo: FooConst,
bar: BarConst,
}

let b: FooBar = {
foo: "foo",
...```

lost scroll
#

BarConst is a string
so in FooBar, the bar property is also a string (since typeof BarConst)
so in c, bar is also a string, so it accepts zzz

#

@dry fable

dry fable
#

The 'typeof' is because trying to use it without typeof gives 'FooConst' refers to a value, but is being used as a type here. Did you mean 'typeof FooConst'? - so maybe I just have to solve this in a different way then. 🤔

unique rune
lost scroll
dry fable
#

What I am trying to solve was having different classes with "type" in them, where they would be assigned to constants.. but I keep on having to put it in as a value instead ( 'foo' instead of FooType )

lost scroll
unique rune
#

wow how did manage to figure that out lmao

#

im so lost

dry fable
#

I use plenty of generics, so it's not quite that.. I just want a type to have a fixed value for one property, taken from a constant, instead of having to write it inline as a value

lost scroll
unique rune
#

idk that sounds kinda like discriminated unions to me

unique rune
#

if not that, you might want to show a playground of that instead

dry fable
#

typeof works, but it only works if the const is defined without a type. which is what i was trying to understand why

unique rune
#

const a = "foo" has a's type as "foo", not string

#

with consts, ts gets as narrow as possible

#

that's what as const does

dry fable
unique rune
#

you couldve used the playground (or i guess hover over FooConst)

#
const FooConst = "foo";
//    ^?
#

!ts

leaden bladeBOT
#
const FooConst = "foo";
//    ^? - const FooConst: "foo"
dry fable
#

ok well that answers my question then, I'll rephrase and ask later if I can frame it better 🙂

lost scroll
#

if you want to set a constraint without actually changing the type, you might want to use the satisfies operator

dry fable
#

yes I noticed that was added in 4.9 - didn't have time to dive into it yet. will have a look

#

thanks @lost scroll @unique rune