Search code examples
typescript

Value type to represent any string, number or boolean


What is the best way to define a property which can take any of string,number and boolean primitive values. I need a property to accept any of these primitive type as value from an html input field (which can be text/int/bool). having any miss type safety I was looking for (specifically, it should not be object, function type).


Solution

  • You can define a function that accepts those, not a property.

    To make the function specifically only accept string, number and boolean you would use an overload. The implementation signature (which is typed any) isn't actually callable, so it doesn't allow other types.

    class Example {
        storeMyThing(input: number): void;
        storeMyThing(input: boolean): void;
        storeMyThing(input: string): void;
        storeMyThing(input: any) {
            console.log(typeof input);
            console.log(input);
        }
    }
    
    var example = new Example();
    
    // Yes
    example.storeMyThing(1);
    example.storeMyThing(true);
    example.storeMyThing('String');
    
    // No
    example.storeMyThing(['Arr', 'Arr']);
    example.storeMyThing({ prop: 'val'});