#Can I avoid a type predicate or type assertion in this code?

21 messages · Page 1 of 1 (latest)

echo trenchBOT
#
bawdyinkslinger#0

Preview:```ts
const logLevels = ['error', 'warn', 'info', 'debug'] as const;
export type LogLevel = (typeof logLevels)[number];

declare function getLogLevelFromEnvironmentVariable(): LogLevel; // will this implementation require a type predicate or type assertion? e.g.:
...```

iron elk
#

!ts

echo trenchBOT
#
const logLevels = ['error', 'warn', 'info', 'debug'] as const;
export type LogLevel = (typeof logLevels)[number];

declare function getLogLevelFromEnvironmentVariable(): LogLevel; // will this implementation require a type predicate or type assertion? e.g.:

const isValidLogLevel = (input: string): input is LogLevel => {
  return logLevels.includes(input /* do I need a type assertion? */ as LogLevel);
};```
iron elk
smoky summit
#

!:includes

echo trenchBOT
#
retsam19#0
`!retsam19:includes`:

The type of Array.prototype.includes assumes that you're using the string to check something about the array. If you're trying to do the reverse, a modified type signature is useful:

function includes<S extends string>(haystack: readonly S[], needle: string): needle is S {
    const _haystack: readonly string[] = haystack;
    return _haystack.includes(needle)
}

declare const x: string;
if(includes(["a", "b", "c"], x)) {
    // x is "a" | "b" | "c"
}
iron elk
smoky summit
#

oh the type

#

LogLevel isnt a value so you can't do that anyway

iron elk
#

but...

#

the documentation says:

For example, with the code: "value" in x. where "value" is a string literal and x is a union type.

smoky summit
#

all types get erased at compile time

smoky summit
#

x is a variable with a union type

iron elk
iron elk
smoky summit
#

prolly yeah

iron elk
#

haha, okay, thanks

#

that includes is pretty clever, thanks