Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

write a typescript type that only accepts numbers that are divisible by 32

  1. User

    write a typescript type that only accepts numbers that are divisible by 32

  2. Assistant

    You can create a custom TypeScript type using the type keyword and the number type. Here's an example of a type that only accepts numbers divisible by 32:

    type DivisibleBy32 = number & { __divisibleBy32: true };
    
    function foo(num: DivisibleBy32): void {
        // Function implementation goes here
    }
    
    foo(32); // Valid
    foo(64); // Valid
    foo(96); // Valid
    
    foo(33); // Invalid
    foo(55); // Invalid
    foo(100); // Invalid
    

    In this example, we define a custom type DivisibleBy32 as a union of number type and an object type __divisibleBy32 with the value true. This way, only numbers that are divisible by 32 and have this extra object property can be assigned to the DivisibleBy32 type.

    When you try to call the foo() function with a number that is not divisible by 32, TypeScript will throw a compilation error.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.