Typescript 具有类型或接口的类型断言
怎么做Typescript 具有类型或接口的类型断言,typescript,Typescript,怎么做 type Brain = ...; type Body = ...; f = (part: Brain| Body) => { // An error occurs here: // Brain' only refers to a type, but is being used as a value here. if (typeof part === Brain) { // do something... } } 如果您需要更多信息,请告诉我。类型别名和接口仅
type Brain = ...;
type Body = ...;
f = (part: Brain| Body) => {
// An error occurs here:
// Brain' only refers to a type, but is being used as a value here.
if (typeof part === Brain) {
// do something...
}
}
如果您需要更多信息,请告诉我。类型别名和接口仅在编译时存在,因此您无法基于它们执行任何运行时检查 根据您的需要,您可以使用以下几种方法之一:
操作符用作类型保护
运算符检查是否存在仅存在于以下类型之一中的属性:
type Brain = { brainSize: number, eyeColor: string };
type Body = { weight: number };
const f = (part: Brain | Body) => {
if ('brainSize' in part) {
part.brainSize //ok
part.eyeColor // also ok
} else {
part.weight //ok
}
}
如果您想额外确保,可以使用自定义类型保护手动检查接口的所有属性:
type Brain = { brainSize: number, eyeColor: string };
type Body = { weight: number };
function isBrain(part: unknown): part is Brain {
let maybeBrain = part as Brain
return maybeBrain
&& typeof maybeBrain.brainSize === "number"
&& typeof maybeBrain.eyeColor === "string"
}
const f = (part: Brain | Body) => {
if (isBrain(part)) {
part.brainSize //ok
part.eyeColor // also ok
} else {
part.weight //ok
}
}
最严格的选择是使用typescript is
,以生成类似于out-type-guard的代码,但这意味着将默认编译器替换为ttypescript
,我个人不建议这样做。类型别名和接口仅在编译时存在,因此,您不能基于它们执行任何运行时检查
根据您的需要,您可以使用以下几种方法之一:
非常严格:使用一些东西来允许插件生成一些额外的代码来执行精确的类型接口检查
足够严格:使用自定义类型保护来检查值是否为特定类型
Lax:将
中的操作符用作类型保护
最简单的方法是使用
中的运算符检查是否存在仅存在于以下类型之一中的属性:
type Brain = { brainSize: number, eyeColor: string };
type Body = { weight: number };
const f = (part: Brain | Body) => {
if ('brainSize' in part) {
part.brainSize //ok
part.eyeColor // also ok
} else {
part.weight //ok
}
}
如果您想额外确保,可以使用自定义类型保护手动检查接口的所有属性:
type Brain = { brainSize: number, eyeColor: string };
type Body = { weight: number };
function isBrain(part: unknown): part is Brain {
let maybeBrain = part as Brain
return maybeBrain
&& typeof maybeBrain.brainSize === "number"
&& typeof maybeBrain.eyeColor === "string"
}
const f = (part: Brain | Body) => {
if (isBrain(part)) {
part.brainSize //ok
part.eyeColor // also ok
} else {
part.weight //ok
}
}
最严格的选择是使用typescript is
,以生成类似于out-type-guard的代码,但这意味着用ttypescript
替换默认编译器,我个人不建议这样做。是否有方法断言由字符串组成的类型?e、 g:型式试验=“T”|“e”|“S”|“T”;f(“T”);f(str)=>str==T@Jilladme unusre您要问的是,如果str
属于Test
类型或string
str==“T”
将缩小值,如果在if
中使用,是否有方法断言由字符串组成的类型?e、 g:型式试验=“T”|“e”|“S”|“T”;f(“T”);f(str)=>str==T@Jilladme unusre如果str
类型为Test
或string
str==“T”
在if
中使用,则会缩小值