Built-in Functions in TypeScript
This article explains built-in functions in TypeScript.
YouTube Video
Built-in Functions in TypeScript
Built-in functions in TypeScript are convenient functions provided to perform everyday operations concisely. These are standard JavaScript functions with added type safety, making them particularly useful when coding in TypeScript. Here, we will explain in detail some important built-in functions, their usage, and type specification.
What are Built-in Functions?
TypeScript's built-in functions are based on standard JavaScript functions. Applying TypeScript's type system enhances type checking and autocomplete. The main functions include the following:.
parseInt()
parseFloat()
isNaN()
isFinite()
Number()
String()
Array()
Array.isArray()
eval()
encodeURI()
decodeURI()
setTimeout()
setInterval()
These functions are widely used in TypeScript projects for concise data conversion and evaluation.
parseInt()
parseInt()
is a function used to convert a string to an integer. You can specify the radix (such as binary, decimal) as the second argument. In TypeScript, you can specify the type as follows:.
1function stringToInt(value: string, radix: number = 10): number {
2 const result: number = parseInt(value, radix);
3 if (isNaN(result)) {
4 throw new Error('Invalid number format');
5 }
6 return result;
7}
8
9console.log(stringToInt("42")); // 42
10console.log(stringToInt("101010", 2)); // 42 (converted from binary)
- Specify the input is a string with
value: string
- The return value is explicitly specified as a
number
type.
parseFloat()
parseFloat()
is a function used to convert a string to a floating-point number.
1function stringToFloat(value: string): number {
2 const result: number = parseFloat(value);
3 if (isNaN(result)) {
4 throw new Error('Invalid number format');
5 }
6 return result;
7}
8
9console.log(stringToFloat("3.14")); // 3.14
10console.log(stringToFloat("2.71828")); // 2.71828
parseFloat()
can correctly parse numbers including decimal points.- By specifying the type, you can receive a warning during type checking if the input is not a number.
isNaN()
isNaN()
is a function that determines if the given value is NaN
(Not-a-Number). An example usage in TypeScript is as follows:.
1function checkNaN(value: unknown): boolean {
2 return isNaN(Number(value));
3}
4
5console.log(checkNaN("hello")); // true
6console.log(checkNaN(123)); // false
- The
unknown
type is a generic type that can accept any type. - Convert to a number using the
Number()
function, and check if the result isNaN
.
isFinite()
isFinite()
determines if a value is finite.
1function isValueFinite(value: unknown): boolean {
2 return isFinite(Number(value));
3}
4
5console.log(isValueFinite("100")); // true
6console.log(isValueFinite(Infinity)); // false
- This function also uses
Number()
to convert the value to a number before determining.
Number()
The Number()
function converts strings or boolean values to numbers.
1function convertToNumber(value: string | boolean): number {
2 return Number(value);
3}
4
5console.log(convertToNumber("42")); // 42
6console.log(convertToNumber(true)); // 1
- In this example, a union type
string | boolean
is used to specify that the argument is either a string or a boolean.
String()
The String()
function converts numbers or boolean values to strings.
1function convertToString(value: number | boolean): string {
2 return String(value);
3}
4
5console.log(convertToString(123)); // "123"
6console.log(convertToString(false)); // "false"
- In this example, a function is created that accepts a union of
number | boolean
type and converts the result to a string.
Array()
The Array()
function is used to create a new array. Additionally, it provides many useful methods for creating subarrays from existing arrays or extracting specific elements.
1function createArray(): Array<number> {
2 return Array(1, 2, 3, 4, 5); // 新しい配列を作成
3}
4
5function getSubArray(array: Array<number>): Array<number> {
6 return array.slice(1, 4); // サブ配列を作成
7}
8
9const numbers = createArray();
10console.log(numbers); // [1, 2, 3, 4, 5]
11
12const subArray = getSubArray(numbers);
13console.log(subArray); // [2, 3, 4]
- This example demonstrates how to create a new array using the
Array()
function and create a subarray using theslice()
method.
Array.isArray()
Array.isArray()
determines whether the given value is an array.
1function checkArray(value: unknown): boolean {
2 return Array.isArray(value);
3}
4
5console.log(checkArray([1, 2, 3])); // true
6console.log(checkArray("Not an array")); // false
- Using the
unknown
type, we accept any type while checking if it's an array.
eval()
The eval()
function evaluates a string as an expression and returns the result. However, it is not recommended for use due to security and performance risks.
1function evaluateExpression(expression: string): any {
2 return eval(expression);
3}
4
5console.log(evaluateExpression("2 + 3")); // 5
6console.log(evaluateExpression("'Hello ' + 'World!'")); // "Hello World!"
- In this example, an expression provided as a string is evaluated using
eval
, and the result is outputted.
encodeURI()
The encodeURI()
function encodes the entire URL and escapes certain characters.
1const uri = "https://example.com/page?name=John Doe&age=30";
2const encodedURI = encodeURI(uri);
3
4console.log(encodedURI); // "https://example.com/page?name=John%20Doe&age=30"
- This example encodes spaces into
%20
to generate a safe URL.
decodeURI()
The decodeURI()
function decodes an encoded URL back to its original format.
1const encodedURI = "https://example.com/page?name=John%20Doe&age=30";
2const decodedURI = decodeURI(encodedURI);
3
4console.log(decodedURI); // "https://example.com/page?name=John Doe&age=30"
- This example decodes an encoded URL string back to the original URL.
setTimeout()
The setTimeout()
function executes a specified function after the given delay time (in milliseconds).
1setTimeout(() => {
2 console.log("Executed after 2 seconds");
3}, 2000);
- This example displays a message after 2 seconds.
setInterval()
The setInterval()
function repeatedly executes a specified function at the specified interval (in milliseconds).
1let count = 0;
2const intervalId = setInterval(() => {
3 count++;
4 console.log(`Interval executed ${count} time(s)`);
5 if (count === 3) {
6 clearInterval(intervalId); // Stops the interval after 3 executions
7 }
8}, 1000);
- This example displays a message at one-second intervals and stops after being executed three times.
Conclusion
TypeScript's built-in functions enable safer and more efficient coding by adding type safety to standard JavaScript functions. These functions simplify everyday programming tasks and improve code readability and maintainability. Each function is used correctly according to its purpose, and by specifying types, it can detect errors in advance, playing an important role in enhancing the reliability of the development process.
By using TypeScript, development can take advantage of static typing while leveraging the flexibility of JavaScript.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.