Typescript negative type check

前端 未结 3 1903
故里飘歌
故里飘歌 2021-01-12 10:27

In typescript: is it possible to check if type expected type IS NOT some type? Or create an interface that defines methods/props that should not be there?

3条回答
  •  北海茫月
    2021-01-12 11:10

    In typescript: is it possible to check if type expected type IS NOT some type?

    I suspect what you are looking for is runtime types. TypeScript doesn't have a way to do this since there isn't a Standardized way to do this in JavaScript either.

    If you are just looking for simple type guards they work fine e.g.

    function foo(bar: string | number){
        if (typeof bar !== 'string') {
            // TypeScript knows its a number!
            return bar.toPrecision(3);
        }
    }
    

    More

    Type guards : https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html

提交回复
热议问题