gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
write a typescript type that only accepts numbers that are divisible by 32
- User
write a typescript type that only accepts numbers that are divisible by 32
- Assistant
You can create a custom TypeScript type using the
typekeyword and thenumbertype. 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); // InvalidIn this example, we define a custom type
DivisibleBy32as a union ofnumbertype and an object type__divisibleBy32with the valuetrue. This way, only numbers that are divisible by 32 and have this extra object property can be assigned to theDivisibleBy32type.When you try to call the
foo()function with a number that is not divisible by 32, TypeScript will throw a compilation error.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.