部分 T仅适用于内联值 [英] Partial<T> only works with inline values

查看:57
本文介绍了部分 T仅适用于内联值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码表现得像它一样?它是 TypeScript 编译器中的错误还是缺失的功能?

Why does the code below behave like it does? Is it a bug in the TypeScript compiler or missing feature?

class MyType {
  constructor(public readonly value1: string, public readonly value2: number) {
  }  
}

function myFunction(props: Partial<MyType>): void {
  // Do something here    
}

myFunction({ }); // Compiles
myFunction({ value1: 'string', value2: 42 }); // Compiles
myFunction({ wrongValue: true }); // Compile error!!

const myValue1 = {};
const myValue2 = { value1: 'string', value2: 42 };
const myValue3 = { wrongValue: true };

myFunction(myValue1); // Compiles
myFunction(myValue2); // Compiles
myFunction(myValue3); // Compiles, but why?!? I expected this not to compile!

我使用的是 TypeScript 2.1.6 版

I used TypeScript version 2.1.6

推荐答案

您要的是精确类型,已跟踪 这里.

What you are asking for is exact type, which is tracked here.

目前 TypeScript 只会检查对象字面量的过多对象键,主要是检查错字.将对象绑定到变​​量后,TypeScript 不会检查过多的键.

Currently TypeScript will only check excessive object keys for object literal, mainly for typo. After you bind a object to variable, TypeScript will not check excessive keys.

规范:https://github.com/Microsoft/TypeScript/blob/02547fe664a1b5d1f07ea459f054c34e356d3746/doc/spec.md#3115-excess-properties

Partial 有效地为类的字段添加了可选标记.

Partial is effectively add optional mark to the fields of your class.

因此它不会为 myValue3 报告错误.

So it does not report error for myValue3.

这篇关于部分 T仅适用于内联值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆