#Narrowing template literals

5 messages · Page 1 of 1 (latest)

hallow compass
#

Can I narrow this type with template literal, to remove ${number} from the type?

marsh kindleBOT
#
drwarpman#0

Preview:```ts
const LOG_LEVEL = {
ERROR: 0,
WARN: 1,
INFO: 2,
}

const createLogger = (
logLevel: keyof typeof LOG_LEVEL | ${number}
) => {
let level: keyof typeof LOG_LEVEL

if (logLevel in LOG_LEVEL) {
level = logLevel // throws error
}
...```

unreal sundial
#

you can do this but it might not be very satisfying:

marsh kindleBOT
#
mkantor#0

Preview:ts ... if ( logLevel === "ERROR" || logLevel === "WARN" || logLevel === "INFO" ) { level = logLevel } ...

unreal sundial
#

i don't think you can directly check for ```${number}` `` to rule out that possibility, at least not without writing a custom type guard