If you have worked with TypeScript for any amount of time, you have likely run into some sort of type assertion. Many people are familiar with the most common way of asserting types - the : syntax.
const age: number = 21; // ✅ TypeScript is happy with this
const name: string = true; // ❌ TypeScript will not let you assign this value
This is one of the best features of TypeScript and allows you to have much safer code because you can ensure that faulty values are not passed to your variables or functions. However, TypeScript also has some other type assertions. You might have seen as and satisfies being used before.
const age: number = 21; // ✅ TypeScript is happy with this
const anotherAge = 22 as number; // ✅ TypeScript is also happy with this
const oneMoreAge = 23 satisfies number; // ✅ TypeScript is happy with this
So what is the difference? There are a few, namely in how TypeScript enforces the types. The colon (:) syntax is the safest in some ways because it typecasts the variable to have to be of a certain type, but let's consider this example.
const age: number = 21; // ✅ TypeScript is happy with this
const name: string = true as string; // ✅ TypeScript is also happy with this
The as and satisfies keywords as used to give TypeScript information about a value. This is where the difference between the two comes in. When using as, we are telling TypeScript "this value is of this type, trust me bro". However, when we use satisfies we are saying to TypeScript "this value should be of this type, please check for me". If we consider the above example again:
const age: number = 21; // ✅ TypeScript is happy with this
const name: string = true as string; // ✅ TypeScript is also happy with this
const surname: string = false satisfies string; // ❌ TypeScript will not let you assign this value
The as syntax is very useful if you are working in a context where you need to tell TypeScript what type a value is before assigning it to variable or passing it to a function or returning it. The satisfies syntax, on the other hand, is very useful for telling TypeScript that you want to return a value of a certain type and that it should let you know if there is a problem. Here is a good real world example:
interface User {
name: string;
surname: string;
age: number;
}
// Using the "as" syntax. ✅ TypeScript is happy with this
function getUser() {
return { name: 'John', surname: 'Doe', age: 25 } as User;
}
function getUser() {
return {} as User; // ✅ TypeScript is also happy with this
}
// Using the "satisfies" syntax. ✅ TypeScript is happy with this
function getUser() {
return { name: 'John', surname: 'Doe', age: 25 } satisfies User;
}
function getUser() {
return {} satisfies User; // ❌ TypeScript will not allow this
}