首页 > 解决方案 > 键入“除...之外的所有可能的字符串值”

问题描述

是否可以定义一种类型,除了少数指定的字符串值之外,每个字符串值都被分配?我想按照这个(非编译)示例的方式表达一些东西:

type ReservedNames = "this" | "that"
type FooName = string - ReservedNames;
const f1 : FooName = "This" // Works
const f2 : FooName = "this" // Should error

标签: typescript

解决方案


这个问题没有通用的解决方案,因为没有办法在打字稿类型系统中表达字符串可以是除列表之外的任何值这一事实。(有人可能认为条件类型Exclude<string, ReservedNames>会起作用,但它不会,它只是返回到 string)。

作为一种解决方法,如果我们有一个函数,并且我们特别希望不允许传入某些常量,我们可以使用条件类型来检查ReservedNames,如果传入的参数是ReservedNames输入参数,那么输入参数是这样的:实际上不可能满足(使用交集类型)。

type ReservedNames = "this" | "that"
type FooName = Exclude<string, ReservedNames>;
const f1 : FooName = "This" // Works
const f2 : FooName = "this" // One might expect this to work but IT DOES NOT as FooName is just evaluates to string


function withName<T extends string>(v: T & (T extends ReservedNames ? "Value is reserved!": {})) {
  return v;
}

withName("this"); // Type '"this"' is not assignable to type '"Value is reserved!"'.
withName("This") // ok

操场


推荐阅读