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

TypeScript如何定义仅接受非空字符串的类型或类属性

TypeScript 定义非空字符串属性的实现方案

可以实现,以下是兼容你需求的实现方案,同时补充原生类型的注意事项:


前置说明

你示例中写的 Exclude<string, ''> 实际无效,因为 Exclude 仅作用于联合类型,string 是基础类型不是联合类型,运算后返回的还是普通 string,无法拦截空字符串赋值。


1. 纯编译期类型校验(仅字面量赋值时报错)

如果只需要编译期拦截空字符串字面量的赋值,可以用以下两种写法:

自定义Not工具类型,完全匹配你期望的第一种写法

// 定义Not工具类型
type Not<T> = T extends '' ? (string extends T ? never : string) : never

class Foo {
   id: string & Not<''>
}

const bar = new Foo()
bar.id = '' // ts compile error
bar.id = 'whatever string you want' // ts compile allowed

通用非空字符串类型定义

// TS 4.1及以上版本可用,适配所有字面量场景
type NonEmptyString = `${string & {}}`

const something1: NonEmptyString = '' // ts compile error
const something: NonEmptyString = 'f' // ts compile allowed
const something2: NonEmptyString = '1' // ts compile allowed

2. 编译+运行双校验方案(更稳妥)

如果需要同时避免运行时被传入空字符串,建议结合类的setter实现:

// 定义标记类型,用于编译期校验
type NonEmptyString = string & { __isNonEmpty?: true }

class Foo {
  // 私有存储属性
  #id: NonEmptyString = 'default' as NonEmptyString

  get id(): NonEmptyString {
    return this.#id
  }

  set id(val: string) {
    // 运行时校验
    if (val.length === 0) {
      throw new Error('id 不允许为空字符串')
    }
    this.#id = val as NonEmptyString
  }
}

const bar = new Foo()
bar.id = '' // 编译期提示类型错误,运行时也会抛出异常
bar.id = 'normal string' // 编译通过,运行时正常赋值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:39:00