Closed3

Deno KVのKeyを型定義したい

lsadsfjlsadsfj

一部固定値を含む型定義をしたい。

具体例を挙げる。
Keyである["country", "japan", "name", "taro"]がある。
このcountryとnameを固定値でjapan, taroはstring型で定義したい。

lsadsfjlsadsfj

サンプルコード

const kv = await Deno.openKv();
type Human = {
  "name": string;
  "age": number;
  "height": number;
};
type HumanKey = ["country", string, "name", string];

const setHuman = (key: HumanKey, value: Human) => {
  kv.set(key, value);
};

const taro: Human = {
  "name": "taro",
  "age": 24,
  "height": 170,
};
const taroKey: HumanKey = ["country", "japan", "name", "taro"];
setHuman(taroKey, taro);

const entries = kv.list({ prefix: [] });
for await (const entry of entries) {
  console.log(entry);
}
このスクラップは3ヶ月前にクローズされました