Friday, 26 May 2017

Typescript: creating a type to represesnt IPv4 addresses

I'm writing a type declaration file for an npm package that's lacking it. I want to make a type to represent an IP, but I started running into trouble once I started to try to verify that the IP is either localhost or four numbers below 255 separated by periods. This is what I have so far:

declare type IP = string | "localhost" | {length: 7} | {length: 8} 
    | {length: 9} | {length: 10} | {length: 11} | {length: 12}
    | {length: 13} | {length: 14} | {length: 15};

I calculated the range of lengths of IPs using 0.0.0.0 and 255.255.255.255. There has to be a better way of going about this though. How can I check if the IP given is valid, and how can I reduce the multiple length conditions down to possibly one?



via kpimov

No comments:

Post a Comment