#General Purpose TypeGaurd

11 messages · Page 1 of 1 (latest)

keen mango
#

I want to make a general purpose typegaurd. The docs(https://basarat.gitbook.io/typescript/type-system/typeguard) usually split this into multiple steps, one for each type/interface

    foo: number;
    common: string;
}
function isFoo(arg: any): arg is Foo {
    return arg.foo !== undefined;
}```
and then another function to act on it 
```function doStuff(arg: Foo | Bar) {
    if (isFoo(arg)) {
        console.log(arg.foo); // OK
        console.log(arg.bar); // Error!
    }
    else {
        console.log(arg.foo); // Error!
        console.log(arg.bar); // OK
    }
}```

Is it impossible to do something like this instead: ```function isInterfaceMatch(arg: any, match: Interface): arg is match{
  return true
}

isInterfaceMatch(x, Foo)```
#

forgive me if I'm completely misunderstanding arg is Foo, I assume its some kind of boolean/conditional thingy

amber ore
#

What you want is an assertion.

function isString(value: unknown): asserts value is string {
    if (typeof value !== 'string') throw new Error('...')
}

declare const foo: unknown

isString(foo)
foo.toLowerCase()
supple tapir
#

what would the implementation of such a function be like? if it's literally return true, then you're doing the same thing as a type assertion (as)

#

oops, sorry missed Burrito's reply before i sent mine

#

though i'm not sure they really answered your question. i think you were asking more about not having to specify ahead of time what Interface is?

supple tapir
latent groveBOT
#
mkantor#0

Preview:```ts
function yikes<T>(arg: unknown): arg is T {
return true
}

const x = Math.random() > 0.5 ? 1 : "one"
// we'll always go into this if, since yikes always returns true
if (yikes<string>(x)) {
// this will throw an error 50% of the time
x.toUpperCase()
}

// the above has the same behavior as this:
;(x as string).toUpperCase()```

charred token
#

@keen mango The main thing is that types do not exist at runtime. isInterfaceMatch(arg: any, match: Interface) doesn't make sense because you can't pass an interface to a function because there's nothing to pass.

amber ore
#

Ah my bad, misread the question.

keen mango
#

thanks guys, I found this massive thread about the issue last night https://stackoverflow.com/questions/14425568/interface-type-check-with-typescript for anyone interested there seemed to be a couple extremely hacky ways to do it, and a lot of salt. But yea, I didn't fully grasp the whole compile/runtime separation thing until now.