Is there a type in TypeScript for anything except functions?

后端 未结 4 1315
孤独总比滥情好
孤独总比滥情好 2020-12-01 21:49

I would like to express that a paremeter should be an object or a simple value type (number, bool, string, etc.), but not a function.

If I use Object, t

4条回答
  •  伪装坚强ぢ
    2020-12-01 22:16

    Here is an approach that defines all valid (non-function) values and then uses a recursive definition. I think this works for my case and hopefully for anyone else who comes across this question.

    Example on Typescript Playground

    type NoFunctionValue =
        boolean
        | string
        | number
        | null
        | undefined
        | NoFunctionObject
        | NoFunctionArray
    
    interface NoFunctionObject {
        [key: string]: NoFunctionValue
    }
    
    interface NoFunctionArray extends Array { }
    
    // Try putting a function anywhere in here to see error
    const text: NoFunctionObject = {
        bool: true,
        str: 'string',
        num: 7,
        nul: null,
        undef: undefined,
        arr: [true, 'string', 7, null, undefined],
        obj: {
            bool: true,
            str: 'string',
            num: 7,
            nul: null,
            undef: undefined,
            arr: [true, 'string', 7, null, undefined]
        }
    } 
    

提交回复
热议问题