Typescript tipe freshness 更嚴(yán)格對象字面量檢查
引言
Typescript 是結(jié)構(gòu)化的類型系統(tǒng),那么對于對象來說,如果 A 具有 B 的所有屬性,并且屬性對應(yīng)的類型相匹配,那么 A 就能賦值給 B
type A = {
name:string;
age:number;
}
type B = {
name:string
}
declare let a:A
declare let b: B
b = a
但是其中有一個例外的情況,會強制 a、b 具有完全相同的結(jié)構(gòu),被稱為 freshness,也被稱為更嚴(yán)格的對象字面量檢查
let b: {
name:string
}
b ={name:'1',age:1}
/*
Type '{ name: string; age: number; }' is not assignable to type '{ name: string; }'.
Object literal may only specify known properties, and 'age' does not exist in type '{ name: string; }'
*/
function freshness({name}:{name:string}){
return 1
}
freshness({name:'du',age:1});
/*
Argument of type '{ name: string; age: number; }' is not assignable to parameter of type '{ name: string; }'.
Object literal may only specify known properties, and 'age' does not exist in type '{ name: string; }'
*/
嚴(yán)格檢查存在缺點
之所以有這樣的嚴(yán)格檢查是因為存在以下兩個缺點:
1.結(jié)構(gòu)化類型系統(tǒng)非常方便,但是它可能讓你誤以為某些函數(shù)接收的比他實際需要的多
function logName(something: { name: string }) {
console.log(something.name);
}
logName({ name: 'matt', job: 'being awesome' })
2.在實現(xiàn)此功能之前 Typescript 并不能很好的檢測出對象中的錯誤,特別是指定可選類型時
interface TextOptions {
alignment?: string;
color?: string;
padding?: number;
}
function drawText(opts: TextOptions) { ... }
// None of these were errors before
drawText({ align: 'center' }); // Oops
drawText({ colour: 'grey' }); // Oops
drawText({ pading: 32}); // Oops
如上例子可能只是拼錯了而已,但是在此之前 Typescript 并不能檢測出來
具體規(guī)則而言
- 每個對象字面量都被認(rèn)為是新鮮的
- 當(dāng)一個新的字面量對象被分配給一個變量或者傳遞給一個非空的目標(biāo)類型參數(shù)時,如果對象指定了目標(biāo)類型中不存在的屬性,那就是一個錯誤
- 在一個類型斷言中,或者當(dāng)一個對象字面的類型被擴大時,新鮮感就會消失
var x: { foo: number };
x = { foo: 1, baz: 2 }; // Error, excess property `baz`
var y: { foo: number, bar?: number };
y = { foo: 1, baz: 2 }; // Error, excess or misspelled property `baz`
當(dāng)新鮮類型被捕獲到變量中時,不會發(fā)生錯誤
var x: { foo: number };
x1 = { foo: 1, baz: 2 };
x = x1;
var y: { foo: number, bar?: number };
y1 = { foo: 1, baz: 2 };
y = y1;
參考: jkchao.github.io/typescript-…
以上就是Typescript tipe freshness 更嚴(yán)格對象字面量檢查的詳細內(nèi)容,更多關(guān)于Typescript tipe freshness對象字面量檢查的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
js jquery ajax的幾種用法總結(jié)(及優(yōu)缺點介紹)
本篇文章只要介紹了js jquery ajax的幾種用法總結(jié)(及優(yōu)缺點介紹),需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01
微信小程序?qū)崿F(xiàn)觸底加載與下拉刷新的示例代碼
本文主要介紹了微信小程序?qū)崿F(xiàn)觸底加載與下拉刷新的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05
ros::spin() 和 ros::spinOnce()函數(shù)的區(qū)別及詳解
這篇文章主要介紹了ros::spin() 和 ros::spinOnce()函數(shù)的區(qū)別及詳解的相關(guān)資料,本文介紹的非常詳細,具有參考借鑒價值,感謝興趣的朋友一起看看吧2016-10-10
javascript中的undefined 與 null 的區(qū)別 補充篇
在Javascript中有兩個值用來代表類似空值的概念,undefined和null,這兩個很容易被混淆,他們表示的是兩個不同的概念。2010-03-03
引入autocomplete組件時JS報未結(jié)束字符串常量錯誤
在引入jQuery的autocomplete組件時,遇到j(luò)s報未結(jié)束字符串常量錯誤,原因及解決方法如下,大家可以參考下2014-03-03

