首页 > 解决方案 > 打字稿:“如果这是故意的,请先将表达式转换为‘未知’。”

问题描述

当将一个类型转换为另一种类型时,Typescript 编译器通常会告诉我先转换为未知类型。我一直不明白这背后的原因。有人可以解释为什么这是必要的吗?

这是一个例子:

// An Animal is a living thing.
type Animal = { livingThing: true }

// A Dog or Cat type is a subtype of an Animal type.
type Dog = { livingThing: true, woof: true, }
type Cat = { livingThing: true, meow: true, }



// We have a cat and a dog: meow and woof.
const meow:Cat = { livingThing: true, meow: true }
const woof:Dog = { livingThing: true, woof: true }

// We have a living thing.
const someLivingThing:Animal = { livingThing: true }

// Let us assert that a living thing must be a cat.
const isACat:Cat = someLivingThing
//    ^^^^^^(type error 1)

// Trust me, this living thing is a cat. (note 1)
const isACat_trustMe:Cat = someLivingThing as Cat


// A dog pretends to be a cat but fails.
const dog_pretend_cat_failed:Cat = woof as Cat
                                // ^^^^^^^^^^^(type error 2)

// A dog successfully pretending to be a cat.
const dog_pretend_cat_succeed:Cat = woof as unknown as Cat


/*
---------
note 1:
Type casting in action.


type error 1:
[tsserver 2741] [E] Property 'meow' is missing in type 'Animal' but required in type 'Cat'.

type error 2:
[tsserver 2352] Conversion of type 'Dog' to type 'Cat'
                may be a mistake because neither type sufficiently
                overlaps with the other. If this was intentional,
                convert the expression to 'unknown' first. [E]
*/ 

这是这段代码到 Typescript 游乐场的链接

标签: typescript

解决方案


推荐阅读