0

Good day everyone,

I am struggling a bit with TypeScript lately, I will go straight to the point

I have this interface and this object as shown below:

interface Beer {
  id:string
  name:string,
  amount: number  //I want the amount to always be a positive number
}


const beerOrder:Beer = {
id:'1234',
name: 'Beer',
amount: -1 //this should not be allowed
}

I want the amount in the Beer interface to always be a positive number, I tried to search around on how you can do that but I failed so far...

If you have any ideas on how to solve this in TypeScript then that would be greatly appreciated!!

Typescript playground link here

Why u do dis
  • 418
  • 4
  • 15
  • @GeneralGrievance So basically nothing like that exists in TS ? Could this be handled manually somehow? I will keep this opened for a bit longer to see if anyone found some other hacky way to do this – Why u do dis Mar 24 '22 at 19:23
  • 2
    [lol](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgEIWsg3gKGc4AEwC5kBnMKUAcz2RDgFsJSKqRqAaOpgewFdwpEP0YAjTMgD0UgJLIA7nHDIwACxR9BYVb2RwANkoCeZZBP3IADrzLAwwAG4oR46DgC+OHAl4gK5hhQAPJQhNCk6JgAvMiOhkRwkAAUuPhExADkAIwATADMACyZ3PgMzKSZUVAlPIwCQsgAtNnSUqpqwGZkagIGhPS8OhaGBrwKEISe+ma+-mAAlADc3mDGViiyZACCCGD8o8YACrb2ThAAPADKyBAAHpAghN2UNAB8yLE394-PyAAGABIsGJgNRQGAPP9kAB+ZDfB4QJ5mf5NYGg8HgKGw5DwAxkFCkSj8Qm4wwElY4NYbZBbE52BzOC4AOVuiOR9FEEigH1iW12+0O9LOTKBWGZULelPCCAMcCgKBggj2wD8cQShCSl1QbN+Zmqb2SEgiaAWpDpp0Z2oA2gAiLTgW0AXQ+PyRf2JKDhOtIWFuUCgvCgpHt9W0BDMICG1kt51tyA8SyAA) – kelsny Mar 24 '22 at 19:32
  • 2
    It's possible with a wrapper function to perform inferences and validation, but it is not possible with just a static type that really does no logic. – kelsny Mar 24 '22 at 19:33
  • 1
    Nope, You have number types and you have specific numbers. You can do crazy things with limited ranges of integers, or what @kelleys suggests, but these will always be funky. And if you do any match, or pull this from any data source that only guarantees `number` then a runtime check will be required. See https://tsplay.dev/wjk21N – Alex Wayne Mar 24 '22 at 19:48
  • You are TypeScript wizards guys! I had no Idea you could do stuff like this in TS, amazing! Really surprised TS team hasn't implemented a type that checks for a positive or negative number though. – Why u do dis Mar 24 '22 at 20:05
  • You could also create a class called PositiveNumber and it only has a _value member that is a number and have the value setter check if the number is negative when assigning the value. If its below 0 set value to 0 or undefined. – Derek Lawrence Mar 24 '22 at 20:50

0 Answers0