...work in progress...
Return type
You are able to define the return type of the function that you're calling. You can check the Basic Types in this link. Later we are going to approach some more complex approches.
Example:
d.ts files
This file provides typescript type information about some API file written in JavaScript, been d standing for Declaration Files. So let's supose that you're consuming some external library function, and wants to know what's the return type of certain function
Generics
Let's use a function example. You know exactly the type that will be returned by that function, so thanks to generic, you can specify it instead of creating a function with static types.
// A generic function to create a Box holding a value of any type
function createBox<T>(value: T): { getValue: () => T, setValue: (newValue: T) => void } {
let internalValue: T = value;
return {
getValue: () => internalValue,
setValue: (newValue: T) => {
internalValue = newValue;
}
};
}
// Example usage of the generic createBox function
const numberBox = createBox<number>(42);
console.log("Number Box Value:", numberBox.getValue());
const stringBox = createBox<string>("Hello, Generics!");
console.log("String Box Value:", stringBox.getValue());
// You can also use the same generic function for other types
const booleanBox = createBox<boolean>(true);
console.log("Boolean Box Value:", booleanBox.getValue());
Non-null assertion operator
TypeScript includes a non-null assertion operator, !, which you can append to the end of an expression when you are confident that the value will never be null or undefined. This allows you to bypass TypeScript's strict null checking for that specific value.
interface User {
id: number;
name?: string; // The name property is optional
}
const user: User = { id: 1, name: "John Doe" };
// TypeScript would normally complain here since name could be undefined,
// but we're sure it's initialized in this context.
console.log(user.name!.toUpperCase()); // Output: JOHN DOE
Top comments (0)