31
loading...
This website collects cookies to deliver better user experience
On
or Off
:type Switch = "On" | "Off"
On
or Off
:const x: Switch = "On"
const y: Switch = "Off"
On
or Off
, typescript will throw an error:const variable = "string";
type tVariable = "string";
// this results to a variable
const val = `This is a concatenated ${variable}`
// while this results to type
type X = `This is a concatenated ${tVariable}`
This is a concatenated string
and a variable of that type can only be assigned to that string.NB: If you tried to use variable instead of a type when defining Template Literal Type, it will throw the following error: 'variable' refers to a value, but is being used as a type here. Did you mean 'typeof variable'?
Switch is On
or Switch is Off
, and have it strongly typed, in that it can only return only those strings. With Template Literal Types, we can define this as follows:type Switch = "On" | "Off"
const x: Switch = "On"
const y: Switch = "Off"
type SwitchStatus = `Switch is ${Switch}`;
Switch is On
and Switch is Off
:L1-H1
and the last gets L3-H3
types, as shown below.type SquareBoxes = "L1-H1" | "L1-H2" | "L1-H3" | "L2-H1" | "L2-H2" | "L2-H3" | "L3-H1" | "L3-H2" | "L3-H3";
type length = "1" | "2" | "3";
type SmallerBoxes = `L${length}-H${length}`
// 16 boxes
type length = "1" | "2" | "3" | "4";
// 25 boxes
type length = "1" | "2" | "3" | "4" | "5";
// 4 boxes
type length = "1" | "2";
Person
, which has two properties - name
and age
.type Person = {
name: string;
age: number;
}
name
or age
i.e. nameChanged
or ageChanged
. We can create a new type, that will take type Person
as a generic, and for each property of type Person
, we will add new properties with Changed
appended the original properties of type Person i.e. nameChanged
and ageChanged
. We will used template literal types to create a new property by appending Changed
to the property name.type WithPersonChangedEvents<Type> = {
[Property in keyof Type as `${string & Property}Changed`]: (newValue: Type[Property]) => void;
} & Type;
NB: The above example uses some advanced typescript technique for manipulating types on top of Template Literal Types which you can learn more here.
const person: WithPersonChangedEvents<Person> = {
name: "Name",
age: 20,
nameChanged: (newName) => console.log(newName),
ageChanged: (newAge) => console.log(newAge),
};
person.ageChanged(21); // Logs: 21
person.nameChanged("new Name"); // Logs: "new Name"
person
has 4 properties, with 2 being the added methods.