简体   繁体   English

为什么流类型转换不能按预期对字符串文字起作用

[英]Why flow type casting not working for string literal as expected

For the below example why type casting is not working in Flowtypes?对于下面的示例,为什么类型转换在 Flowtypes 中不起作用? What should be an ideal way of doing it?理想的做法应该是什么?

type typeA = {
  name: 'ben' | 'ken',
};
type typeB = {
  name: string,
};
const objA: typeA = { name: 'ben' };
const objB: typeB = objA;

It gives error它给出了错误

Cannot assign `objA` to `objB` because in property `name`: Either  string [1] is incompatible with  string literal `ben` [2]. Or  string [1] is incompatible with  string literal `ken` [3].

However, for typescript, it is fine.但是,对于 typescript,没问题。

This is actually a TypeScript flaw IMO and Flow does it right.这实际上是一个 TypeScript 缺陷 IMO,Flow 做得对。 Let's see why:让我们看看为什么:

type A = {
  name: 'ben' | 'ken';
}

type B = {
  name: string;
}

const a: A = { name: 'ben' }
const b: B = a;

b.name = 'jen';

console.log({ a });
// this logs { a: { name: 'jen' } } <- see how a.name has an invalid value!

In JS when you write b = a means that b is an "alias" for a and in fact they're the same object.在 JS 中,当您编写b = a时,表示ba的“别名”,实际上它们是相同的 object。

So if you make changes to b then those changes also reflect on a , so if you're permitted to "lean" the name type definition from a given list of strings to a general string, you can go and change a.name with "illegal" or better unwanted values!因此,如果您对b进行更改,那么这些更改也会反映在a上,因此,如果您被允许将name类型定义从给定的字符串列表“倾斜”为通用字符串,则可以 go 并将a.name更改为 "非法”或更好的不需要的值!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM