You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Deno中如何断言string实例?遇类型与值矛盾难题

在Deno中断言字符串类型的正确方式

在Deno中尝试断言变量为字符串类型时,会遇到以下矛盾问题:

第一次尝试使用string作为断言参数:

import {
  assertInstanceOf
} from "https://deno.land/std@0.174.0/testing/asserts.ts";

assertInstanceOf( "foo", string );

触发TypeScript报错:

error: TS2693 [ERROR]: 'string' only refers to a type, but is being used as a value here.
assertInstanceOf( "foo", string );
                         ~~~~~~
    at file:///home/jmerelo/Code/my-stackoverflow-examples/js/string-assert.ts:6:26

改用String构造函数作为参数后:

assertInstanceOf( "foo", String );

又出现断言失败:

Uncaught error from ./string-assert.ts FAILED

 ERRORS 

./string-assert.ts (uncaught error)
error: AssertionError: Expected object to be an instance of "String" but was "string".

问题原因

assertInstanceOf的作用是断言某个值是构造函数的实例对象,但JavaScript中原始类型string和String构造函数创建的包装对象是完全不同的两类值:"foo"是原始字符串,并非String的实例,只有通过new String("foo")创建的包装对象才符合String实例的断言条件。


正确解决方案

使用Deno标准库中专门针对字符串类型的断言函数assertString,无需纠结实例与原始类型的差异:

import {
  assertString
} from "https://deno.land/std@0.174.0/testing/asserts.ts";

assertString( "foo" );

如果需要临时用类型检查的方式实现,也可以直接结合typeof和通用断言函数:

import { assert } from "https://deno.land/std@0.174.0/testing/asserts.ts";

assert( typeof "foo" === "string" );

优先推荐使用assertString,它是标准库专为字符串类型断言设计的API,语义更清晰,也更符合测试断言的最佳实践。

内容的提问来源于stack exchange,提问作者jjmerelo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:55:16