本文介绍了键入“除...之外的每个可能的字符串值";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to define a type that may have every string-value assigned except a few specified ones? I would like to express something along the lines of this (non-compiling) example:

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

推荐答案

这在 Typescript 中目前是不可能的,但是如果将具体的字符串值添加为FooName 的一个参数.

This isn't currently possibly in Typescript, however you can create a generic type that can handle many of the practical use cases if you add the concrete string value as a parameter of FooName.

type ReservedNames = "this" | "that"
type NotA<T> = T extends ReservedNames ? never : T
type NotB<T> = ReservedNames extends T ? never : T
type FooName<T> = NotA<T> & NotB<T>

const f1: FooName<'This'> = 'This' // works
const f2: FooName<'this'> = 'this' // error

const f3: FooName<string> = 'this' //error
const f4: FooName<any> = 'this' // error
const f5: FooName<unknown> = 'this' // error

并且在函数中,如果您在字符串值上使函数通用,它会按预期工作:

And in a function it works as expected if you make the function generic on the string value:

function foo<T extends string> (v: FooName<T>) {
  ...
}

foo('this') // error
foo('This') // works

这篇关于键入“除...之外的每个可能的字符串值";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 13:51