{"id":14187,"date":"2022-11-17T05:31:58","date_gmt":"2022-11-17T11:31:58","guid":{"rendered":"https:\/\/upmostly.com\/?p=14187"},"modified":"2022-11-17T05:31:59","modified_gmt":"2022-11-17T11:31:59","slug":"primitive-types-in-typescript","status":"publish","type":"post","link":"http:\/\/upmostly.com\/typescript\/primitive-types-in-typescript","title":{"rendered":"Primitive Types in TypeScript"},"content":{"rendered":"\n<p><a href=\"https:\/\/upmostly.com\/tutorials\/what-is-typescript-in-react-and-how-to-use-it\" target=\"_blank\" data-type=\"URL\" data-id=\"https:\/\/upmostly.com\/tutorials\/what-is-typescript-in-react-and-how-to-use-it\" rel=\"noreferrer noopener\">TypeScript<\/a> provides some useful primitive types that you&#8217;ll be using every day. In this article, I&#8217;ll explain them, what they&#8217;re for, and the TypeScript-specific primitives.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">number<\/h2>\n\n\n\n<p>The number type works as you expect in TypeScript, covering all the ways JavaScript allows you to  represent a number:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">let n: number;\nn = 3; \/\/Integer\nn = 3.14; \/\/Floating point\nn = 3.14e2; \/\/exponent\nn = 0b0011; \/\/Binary\nn = 0xc0ff33; \/\/Hexadecimal\nn = 0o1066; \/\/Octal\nn = 22 \/ 7;<\/code><\/pre>\n\n\n\n<p>You can also easily convert a number to a string in TypeScript, using the .toString() method of the number:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">const myString: string = n.toString();<\/code><\/pre>\n\n\n\n<p>A cool feature of this function is that it accepts a number as the radix\/base, so you can easily convert a number to a binary string, hexadecimal, or any other base up to 26.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">string<\/h2>\n\n\n\n<p>The string type also acts as it does in JavaScript, storing text values.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">let s: string;\ns = 'Hi from Upweekly!';<\/code><\/pre>\n\n\n\n<p>Strings are also very useful when you combine them with type literals and type unions, letting you define a type as &#8220;only one of these possible strings&#8221;:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">type AlertLevel = 'info' | 'warning' | 'critical';\n\nfunction alert(level: AlertLevel, message: string) {}\n\nalert('info', 'Rebooting the Upmostly quantum mainframe'); \/\/\u2705\nalert('hi', 'This doesnt work'); \/\/\u274e TS2345: Argument of type '\"hi\"' is not assignable to parameter of type 'AlertLevel'.<\/code><\/pre>\n\n\n\n<p>You can convert most types, e.g. numbers, and objects to a string by seeing if they have a .toString() method. You can convert a string to a number using the Number.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">const myNumber = 3.141;\n\nconst myString: string = myNumber.toString();\n\nconst backToNumber: number = Number.parseFloat(myString); \/\/3.141\nconst toInteger: number = Number.parseInt(myString); \/\/3<\/code><\/pre>\n\n\n\n<p>parseInt() also accepts a base as a parameter, letting you convert things like binary and hexadecimal numbers to strings.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">boolean<\/h2>\n\n\n\n<p>Booleans, very simply store true or false values. One pitfall you might run into is converting your boolean to a string. The easiest way to convert these to a string is using a ternary operator:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">const bool: boolean = true;\n\nconst boolToString = bool ? 'true' : 'false';<\/code><\/pre>\n\n\n\n<p>You can of course pick your own representations for the strings.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">BigInt<\/h2>\n\n\n\n<p>BigInts can be used to store numbers too large to be stored in the number primitive, anything bigger than Number.MAX_SAFE_INTEGER.<\/p>\n\n\n\n<p>You can define a bigint by adding an &#8220;n&#8221; onto the end of your number, or by using the BigInt() constructor:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">let myBigInt = 9007199254740992n;\nlet myBigInt2 = BigInt(9007199254740992);<\/code><\/pre>\n\n\n\n<p>The key differences you might deal with when working with Bigint values are:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The Math methods will not work with bigint values<\/li><li>You can&#8217;t mix operations with Bigint and number values without conversion, so be careful about losing precision going from a bigint to a number.<\/li><\/ul>\n\n\n\n<p>TypeScript will even prevent you from comparing bigints and numbers, and its safer to convert one to the other:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">\/\/TS2367: This condition will always return 'false' since the types 'bigint' and 'number' have no overlap.\nif (myBigInt === myNumber) {} \/\/\u274e\n\nif (myBigInt === BigInt(myNumber)) {} \/\/\u2705\nif (Number(myBigInt) === myNumber) {} \/\/\u2705<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">symbol<\/h2>\n\n\n\n<p>Symbol is a primitive data type that represents an immutable, unique value. You can create them using the Symbol constructor.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">const mySymbol1 = Symbol('foo');\nconst mySymbol2 = Symbol('foo');\n\n\/\/TS2367: This condition will always return 'false' since the types 'typeof mySymbol1' and 'typeof mySymbol2' have no overlap.\nif (mySymbol1 === mySymbol2) {\n}\n<\/code><\/pre>\n\n\n\n<p>If you define your symbols as consts, TypeScript may be able to infer that they are unique.<\/p>\n\n\n\n<p>To explicitly state this, TypeScript provides a special &#8220;unique&#8221; keyword. <\/p>\n\n\n\n<p>In this example, TS doesn&#8217;t complain, since they are both of the type symbol.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">const mySymbol1: symbol;\nconst mySymbol2: symbol;\nif (mySymbol1 === mySymbol2) {};<\/code><\/pre>\n\n\n\n<p>We can change the type to &#8220;unique symbol&#8221; to tell TypeScript that we are confident that these are two different symbols:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">const mySymbol1: unique symbol;\nconst mySymbol2: unique symbol;\n\/\/TS2367: This condition will always return 'false' since the types 'typeof mySymbol1' and 'typeof mySymbol2' have no overlap.\nif (mySymbol1 === mySymbol2) {\n}<\/code><\/pre>\n\n\n\n<p>And then TypeScript can be confident that they will never be the same, and throw an error when we try and compare them.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Undefined and Null<\/h2>\n\n\n\n<p>Undefined and null are two TypeScript primitive types used to represent nothing. They act similarly in a lot of cases, the main difference is the intent. Undefined pops up a lot when a variable hasn&#8217;t been defined, or for example when a function returns nothing. &#8220;null&#8221; on the other hand is often used intentfully. While undefined means &#8220;this thing doesn&#8217;t exist\/we haven&#8217;t defined it&#8221;, null is usually used to mean &#8220;this thing exists, but I&#8217;ve specifically left it empty&#8221;.<\/p>\n\n\n\n<p>One place you&#8217;ll see undefined pop up for example is with optional values. Making a function parameter optional in TypeScript actually sets its type to a type union, of whatever type you give and undefined.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">function undefinedExample(maybeUndefined?: number) {\n    \/\/maybeUndefined: number | undefined\n}\n\nundefinedExample(10);\nundefinedExample(undefined);\nundefinedExample();\n\nfunction nullExample(maybeNull: number | null) {}\n\nnullExample(10);\nnullExample(null);\nnullExample() \/\/\u274e TS2554: Expected 1 arguments, but got 0.<\/code><\/pre>\n\n\n\n<p>You can see the difference here, not providing our variable &#8220;maybeUndefined&#8221; gives it a value of undefined. We can explicitly pass it undefined, but there&#8217;s no use. <\/p>\n\n\n\n<p>With the null example, we can&#8217;t just omit the parameter, we have to explicitly pass in null.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Void and Never<\/h2>\n\n\n\n<p>TypeScript introduces two new ways to represent nothing, with Void and Never. If you&#8217;ve used any other type languages, you&#8217;re probably familiar with void. It represents a function that returns nothing.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">function logInCaps(message: string): void {\n    console.log(message.toUpperCase());\n}\n\n\/\/vs\n\nfunction toCaps(message: string): string {\n    return message.toUpperCase();\n}<\/code><\/pre>\n\n\n\n<p>Never is an interesting new type, it represents something that should never happen. <\/p>\n\n\n\n<p>This could mean for example an infinite loop:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">function infiniteLoop(): never {\n    while (true) {\n        console.log('Hi');\n    }\n}<\/code><\/pre>\n\n\n\n<p>Or for example if you use infer with a type union, if a type evaluates to never, it will get removed from the type union, since it should never exist.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Any and Unknown<\/h2>\n\n\n\n<p>In TypeScript, <a href=\"https:\/\/upmostly.com\/typescript\/what-is-the-any-type-in-typescript\" target=\"_blank\" data-type=\"URL\" data-id=\"https:\/\/upmostly.com\/typescript\/what-is-the-any-type-in-typescript\" rel=\"noreferrer noopener\">any<\/a> represents any type. If you give a variable a type of any, you can assign anything to it, and do anything with it.<\/p>\n\n\n\n<p>It&#8217;s generally frowned upon to use any, in favour of either giving it a more specific type, or using unknown. This is because there&#8217;s no type checking for any; you can do anything with it, so we lose a lot of the benefit of TypeScript.<\/p>\n\n\n\n<p><a href=\"https:\/\/upmostly.com\/typescript\/what-is-the-unknown-type-in-typescript\" target=\"_blank\" data-type=\"URL\" data-id=\"https:\/\/upmostly.com\/typescript\/what-is-the-unknown-type-in-typescript\" rel=\"noreferrer noopener\">Unknown<\/a> on the other hand doesn&#8217;t let you do anything with it; you need to narrow the type down before you can do something.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">function unknownExample(myUnknown: unknown) {\n    myUnknown; \/\/myUnknown: unknown\n    myUnknown.toString(); \/\/TS2571: Object is of type 'unknown'.\n    if (typeof myUnknown === 'number') {\n        myUnknown; \/\/myUnknown: number\n        myUnknown.toString();\n    }\n}<\/code><\/pre>\n\n\n\n<p>Any means &#8220;I don&#8217;t know what this is so I&#8217;ll just assume I can do x&#8221;, unknown means &#8220;I don&#8217;t know what this is, so I&#8217;ll make sure I check it can do x&#8221;.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Thanks for reading this article on the primitive types in TypeScript. Hopefully, you learnt a bit about the primitive types, any specific TypeScript quirks, and how to convert between them all. If you liked this article, feel free to leave a comment below!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>TypeScript provides some useful primitive types that you&#8217;ll be using every day. In this article, I&#8217;ll explain them, what they&#8217;re for, and the TypeScript-specific primitives. number The number type works as you expect in TypeScript, covering all the ways JavaScript allows you to represent a number: You can also easily convert a number to a [&hellip;]<\/p>\n","protected":false},"author":123,"featured_media":14313,"comment_status":"open","ping_status":"open","sticky":false,"template":"post-tutorial-new.php","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[279],"tags":[],"class_list":["post-14187","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-typescript"],"acf":[],"_links":{"self":[{"href":"https:\/\/upmostly.com\/wp-json\/wp\/v2\/posts\/14187","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/upmostly.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/upmostly.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/upmostly.com\/wp-json\/wp\/v2\/users\/123"}],"replies":[{"embeddable":true,"href":"https:\/\/upmostly.com\/wp-json\/wp\/v2\/comments?post=14187"}],"version-history":[{"count":5,"href":"https:\/\/upmostly.com\/wp-json\/wp\/v2\/posts\/14187\/revisions"}],"predecessor-version":[{"id":14328,"href":"https:\/\/upmostly.com\/wp-json\/wp\/v2\/posts\/14187\/revisions\/14328"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/upmostly.com\/wp-json\/wp\/v2\/media\/14313"}],"wp:attachment":[{"href":"https:\/\/upmostly.com\/wp-json\/wp\/v2\/media?parent=14187"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/upmostly.com\/wp-json\/wp\/v2\/categories?post=14187"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/upmostly.com\/wp-json\/wp\/v2\/tags?post=14187"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}