TS destructuring
Destructuring assignment generally gets used on an object. Basically it splits the properties out and assigns them to local variables. In functions it sometimes gets written in a form that isn’t very readable, but it does get used a lot, so I’m writing it down here.
// define a type
interface FuncOptions {
name: string;
age?: number;
verbose?: boolean;
}
// and the function signature gets clean
function func({ name, age = 18, verbose = false }: FuncOptions) {
// ...
}
Put plainly, this first defines an interface, and that interface is an object holding a few properties. When you define the function, you destructure the elements you need straight out of that object and use the equals sign (=) to give them a default value. The biggest trap here is the FuncOptions at the end: it can be an object you already defined, or an object written right there in the braces, handed to you on the spot.
// the ?: below means an optional property, in other words age can be left out
function createUser({ name, age = 18 }: { name: string; age?: number }) {
// ╰─────┬──────╯ ╰───────────┬────────────╯
// destructuring + default value type annotation
}
createUser({ name: "Alice" }); // age defaults to 18
createUser({ name: "Bob", age: 25 }); // age is 25
On top of that, TypeScript inherits JavaScript’s syntax sugar completely. A classic one is object property shorthand, and the code for it is below:
const adapter = new PrismaD1(db); // 1. the variable is named adapter
// 2. PrismaClient wants a property named adapter in the config object
// 3. the names collide, so you can use the shorthand
new PrismaClient({ adapter });
// same as:
new PrismaClient({ adapter: adapter });
// if the adapter here were named something else, this would stop working
const myD1 = new PrismaD1(db); // the variable is named myD1, so you have to say it explicitly
new PrismaClient({ adapter: myD1 });
// ❌ wrong way to write it:
// new PrismaClient({ myD1 });
// written that way it passes { myD1: myD1 }, but Prisma doesn't know a myD1 property, only adapter.
Translation note. I wrote this in Chinese. This English version is an LLM translation, so the wording is not mine even though the thinking is. Original: TS解构赋值.