admin管理员组文章数量:1401459
I want to have a type that checks if the value is an odd number or not. I tried to find something but I find only hardcoded solutions like odds: 1 | 3 | 5 | 7 | 9
. But I want to know is there a dynamic way to do it only with Typescript.
I know that for example in JS we can find out that the number is odd or not with this expression x % 2 === 1
. I want to know is there a way to define a type with an expression like this.
I want to have a type that checks if the value is an odd number or not. I tried to find something but I find only hardcoded solutions like odds: 1 | 3 | 5 | 7 | 9
. But I want to know is there a dynamic way to do it only with Typescript.
I know that for example in JS we can find out that the number is odd or not with this expression x % 2 === 1
. I want to know is there a way to define a type with an expression like this.
- Can you provide more information, like the code you may be trying to write it as? That may help us understand the problem better. – Daveguy Commented Jun 18, 2021 at 17:04
-
@RobertHovhannisyan generally
x % 2 == 1
is the way to determine whether a number variable is odd. – Daveguy Commented Jun 18, 2021 at 17:05 - 2 @Daveguy OP is attempting to make a type to enforce a number's oddness. – Dave Newton Commented Jun 18, 2021 at 17:06
-
2
@Daveguy A type, as in
const foo: oddInteger
or whatever. – Dave Newton Commented Jun 18, 2021 at 17:09 - 2 I don't think this is possible in TypeScript (or most type systems, even). – Bergi Commented Jun 18, 2021 at 17:14
2 Answers
Reset to default 8Yes, it is possible
type OddNumber<
X extends number,
Y extends unknown[] = [1],
Z extends number = never
> = Y['length'] extends X
? Z | Y['length']
: OddNumber<X, [1, 1, ...Y], Z | Y['length']>
type a = OddNumber<1> // 1
type b = OddNumber<3> // 1 | 3
type c = OddNumber<5> // 1 | 3 | 5
type d = OddNumber<7> // 1 | 3 | 5 | 7
with some limitations, input must be an odd number and cannot exceed 1999 (maximum depth of typescript recursion is only 1000)
playground
Maybe creating a new class can be helpful on this case?
class OddNumber {
value: number;
constructor(value: number) {
if (value % 2 != 0)
throw new Error("Even number is not assignable to type 'OddNumber'.");
this.value = value;
}
};
let oddNumber = new OddNumber(4);
console.log(oddNumber.value); // It will log 4
let evenNumber = new OddNumber(5); // It will throw an exception here
console.log(evenNumber.value);
本文标签: javascriptOnly odd numbers type for TypescriptStack Overflow
版权声明:本文标题:javascript - Only odd numbers type for Typescript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744247776a2597103.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论