表
Table
类表示记录ID的表名。
导入
import { Table } from "@tai-kun/surrealdb/decodeonly-datatypes";import { Table } from "@tai-kun/surrealdb/encodable-datatypes";import { Table } from "@tai-kun/surrealdb/standard-datatypes";
.constructor()
创建一个新的 Table
对象。
new Table(source: string); // decode-only, encodablenew Table(source: string | { name: string }); // standard
参数
source
表名或 Table
对象。如果预设低于standard,则只能传递表名。
返回值
如果通过 new
调用,Table
将返回其实例。
.name
实例 属性 >=decode-only
表名。获取此属性时,字符串不会被转义。
.name: string;
示例
获取此属性时,字符串不会被转义。
import { Table } from "@tai-kun/surrealdb/decodeonly-datatypes";
const table = new Table("foo-bar");console.log(table.name);//-> foo-bar
.toString()
实例 方法 >=encodable
将 Table
对象转换为SurrealQL变量中可用的字符串。
.valueOf()
和 .toJSON()
将返回与该方法相同的结果。
.toString(): string;
参数
无。
返回值
返回表名。
示例
import { Table } from "@tai-kun/surrealdb/encodable-datatypes";
const table = new Table("foo-bar");console.log(table.toString());//-> foo-bar
.toSurql()
实例 方法 >=encodable
将 Table
对象转换为可嵌入SurrealQL的字符串。与 .toString()
类似,但表名将按照SurrealDB的实现进行转义。
.toSurql(): string;
参数
无。
返回值
返回已转义的表名字符串。
示例
import { Table } from "@tai-kun/surrealdb/encodable-datatypes";
const table = new Table("foo-bar");console.log(table.toSurql());//-> `foo-bar`
.clone()
实例 方法 =standard
复制 Table
对象。
.clone(): this;
参数
无。
返回值
返回一个新的 Table
对象。如果继承了 Table
类,则返回该类的实例。
进阶
类型守卫
可以使用 Table
的表名作为类型参数来实现类型安全:
import { Table } from "@tai-kun/surrealdb/standard-datatypes";
function isUserTable(table: unknown): table is Table<"user"> { return table instanceof Table && table.name === "user"}
Table
对象的通用判断
建议使用 isTable
函数来判断值是否为 Table
对象,而无需依赖预设。此函数不使用 instanceof
,因此在验证值的预设未知时非常有用。
import { isTable } from "@tai-kun/surrealdb";