Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何强制TypeScript在此代码上给出错误?_Typescript_Custom Type - Fatal编程技术网

如何强制TypeScript在此代码上给出错误?

如何强制TypeScript在此代码上给出错误?,typescript,custom-type,Typescript,Custom Type,通常在TypeScript中,我定义了相当复杂的类型,所以我从来没有遇到过这个问题,但我找不到一个简单的方法来解决它 type first = number; type second = number; let f: first = 1; let s: second = 2; const func = (arg1: first, arg2: second) => { }; func(s, f); 我希望从这段代码中得到一个错误,因为我使用类型为“first”的第一个参数和类型为“s

通常在TypeScript中,我定义了相当复杂的类型,所以我从来没有遇到过这个问题,但我找不到一个简单的方法来解决它

type first = number;
type second = number;

let f: first = 1;
let s: second = 2;

const func = (arg1: first, arg2: second) => { };

func(s, f);

我希望从这段代码中得到一个错误,因为我使用类型为“first”的第一个参数和类型为“second”的第二个参数定义函数,但是当我调用它时,我传递了两个类型为反转的参数,TypeScript不关心类型名(或别名),只关心类型的形状。两种类型的
first
second
对于编译器来说都是相同的类型,您不会得到错误

事实上,由于结构类型,此代码也可以工作:

interface I1 {
  name: string;
  age: number;
}

interface I2 {
  age: number;
  name: string;
}

var a1: I1;
var a2: I2;

function log(arg1: I1, arg2: I2): void {
  console.log(arg1, arg2);
}

log(a2, a1);

因为,
I1
I2
也是同一类型的别名(两个接口具有相同类型的相同属性)

当前typescript不支持。 作为一种解决方法,人们使用类型标记/品牌:

type First = number & { readonly _tag: unique symbol };
type Second = number & { readonly _tag: unique symbol };

let f = 1 as First;
let s = 2 as Second;

const func = (arg1: First, arg2: Second) => { };
func(s, f);  // Error: Types of property '_tag' are incompatible.

您刚刚为编号创建了一个别名。这就是为什么
first
second
是兼容的。我知道它们是兼容的,但是如果我为月份创建了一个类型,为天创建了一个类型,它们应该都是数字,但我希望TS阻止或警告我将它们的位置切换为参数。目前typescript不支持标称类型。您可以标记或标记@AlekseyL类型。如果你把它写下来作为一个答案,我会接受它,因为它看起来就像我在寻找的那样。如果我创建一个月的类型,一个天的类型,它们应该都是数字,那么TS无法阻止或警告我将它们的位置转换为参数?好吧,你可以为此定义枚举,那样的话你就不能换了。在任何情况下,通过TS,您可以获得intellisense,因此很容易检测到您将天数指定为月份,反之亦然。您还可以将类型月份定义为
type Month=1 | 2 | 3 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12
。这样,您就无法将数字
13
分配为
Month
类型的变量。然而,当两个数字都小于12时,这并不能防止出现错误。在这种情况下,枚举更好。很好的答案!这是一个聪明的变通方法,我在typescript教程中没有提到过。提供名称“”也确实帮助我搜索更多信息!