typescript - 打字稿:“如果这是故意的,请先将表达式转换为‘未知’。”
问题描述
当将一个类型转换为另一种类型时,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 游乐场的链接
解决方案
推荐阅读
- powerbi - DAX Power BI 中按组排名前 2 位
- javascript - 从输入类型文件 HTML/JS 检查 excel 特定格式
- python - 在
灰色 = cv2.cvtColor(帧,cv2.COLOR_BGR2GRAY)? - bash - 如何将脚本中的变量传递给我使用 cat 生成的文件?
- java - Spring Boot with hibernate:创建复合键和多对多关系
- python-3.x - 计算值超过 Dataframe 中特定列的平均值的次数
- c# - 你如何等到所有请求都运行完成
- android - Expo React Native App在android上崩溃
- python - 在熊猫中使用给定的分隔符获取列daframe中所有项目的子字符串
- android - 从对话框返回后,导航 safeArgs 无法导航