当前位置: 首页>数据库>正文

TypeScript中的satisfies操作符应该怎么玩儿?

澶у濂斤紝鎴戣嫃鍏堢敓锛屼竴鍚嶇儹鐖遍捇鐮斻€佷箰浜庡垎浜殑鍓嶇宸ョ▼甯堬紝鎴戞渶鍠滄鐨勪竴鍙ヨ瘽鏄細浣犲彧绠″姫鍔涳紝缁撴灉璁稿凡鍦ㄨ矾涓婏紒

鍓嶈█

TypeScript4.9涓柊寮曞叆浜唖atisfies鎿嶄綔绗︼紝鎸夌収瀹樻柟鐨勮娉曪紝瀹冪敤浜庡湪纭繚鏌愪簺琛ㄨ揪寮忎笌鏌愮绫诲瀷鍖归厤鐨勫悓鏃朵繚鐣欒琛ㄨ揪寮忕殑鏈€鐗瑰畾绫诲瀷浠ヨ繘琛屾帹鐞?/p>

鍦ㄦ垜鐪嬫潵锛屽畠鍜宎s鍏抽敭瀛楃殑鐢ㄦ硶宸笉澶氾紝鎴栬€呰瀹冪殑鍑虹幇鏄as鍏抽敭瀛楃殑涓€绉嶄紭鍖栥€備笅杈规垜浠互鍑犱釜绀轰緥鏉ュ垏韬劅鍙椾笅satisfies鐨勪笉鍚屼箣澶?/p>

绀轰緥涓€

涔嬪墠锛屾垜浠兂瑕佸幓澶嶇敤涓€涓被鍨嬫椂锛屼负浜嗕娇鍏舵弧瓒冲綋涓嬬殑闇€姹傦紝甯稿父闇€瑕佸€熷姪as甯垜浠畬鎴愮被鍨嬫敼閫?/p>

interface MyElement{
    class:string;
    src:string;
}
const a = {
    class:'test'
} as Partial<MyElement>

涓婅竟鐨勪唬鐮侊紝褰撲綘灏濊瘯浠巃.class涓婅皟鐢╰oString()鏂规硶鏃讹紝TypeScript浼氭姤閿欙紝鍥犱负src鏄鏃舵槸涓€涓彲閫夌殑灞炴€э紝鎴戜滑蹇呴』鍦ㄨ皟鐢ㄥ墠娣诲姞?浠ュ畨鍏ㄧ殑璁块棶瀹冦€傞櫎姝や箣澶栵紝鎴戜滑瀵筧.src鐨勮闂篃涓嶄細寮曡捣TypeScript鐨勭被鍨嬮敊璇彁绀?/p>

a.class?.toString()
a.src

瀵逛簬鍓嶈€咃紝澶у鏁版儏鍐典笅杩欓兘鏄彲浠ユ帴鍙楃殑锛屾棤闈炲氨鏄瘡娆¤皟鐢ㄧ殑鏃跺€欓夯鐑︿竴鐐广€備絾鏄浜庡悗鑰呭垯鏈夊彲鑳藉鑷磋嚧鍛芥€ч敊璇€傛瘮濡備綘寮€鍙戜簡鏌愪釜npm鍖咃紝瀹冭繘琛屼簡鎻掍欢鍖栬璁★紝閭d箞姝ゆ椂杩欎釜src灞炴€у氨鏈夊彲鑳藉绗笁鏂瑰紑鍙戣€呬骇鐢熻瀵?/p>

鐜板湪锛屾垜浠娇鐢╯atisfies鏉ヨ繘琛屾敼閫狅紝瀹冧細瀵瑰師绫诲瀷涓庡疄闄呭€肩粨鍚堝悗鎺ㄦ柇鍑轰竴涓柊鐨勭被鍨?/p>

const a = {
    class:'http://'
} satisfies Partial<MyElement> 

姝ゆ椂锛屽綋鎴戜滑鍐嶆璁块棶a.src鏃讹紝TypeScript灏辫兘澶熸纭帹鏂嚭绫诲瀷閿欒銆傚苟涓旀垜浠toString鐨勮皟鐢ㄤ篃涓嶉渶瑕佸啀娣诲姞?绗﹀彿鏉ヨ繘琛屽畧鍗簡

鎺ㄥ箍鏃堕棿锛?/p>

鎴戞湰鏉ヤ竴鐩村湪鎺ㄦ垜鐨勭害瀹氬紡璺敱搴擄紝涓嶈繃鐩墠鐪嬫潵鏀舵晥鐢氬井銆傚鏋滃畠鏄垜鐨勪汉闂寸悊鎯崇殑璇濓紝閭f專绁ㄥ瓙鍒欐槸鎴戠殑闈㈠寘锛屾墍浠ユ垜閫変簡鍑犱釜鎴戣涓烘槸鎴戜滑澶у鏁板墠绔紑鍙戣€呭鏄撳拷鐣ヤ絾鍙堝緢閲嶈鐨勫皬鍐屻€傛湁鎯宠瀛︿範鐨勬帢鍙嬭嚜琛岃喘涔板搱

  • 娣卞叆鍓栨瀽 Node.js 搴曞眰鍘熺悊

  • 鍥捐В缃戠粶鍗忚

  • javascript璁捐妯″紡鍘熺悊涓庡疄鎴?/p>

  • 鍓嶇璋冭瘯閫氬叧绉樼睄

绀轰緥浜?/h2>

鐢变簬绫诲瀷鎺ㄥ€掔殑瀛樺湪锛屾垜浠笉闇€瑕佸幓鎵嬪姩瀹氫箟绫诲瀷

const sp = {
    name:'spp',
    id:410324
}

浣嗚繖鏃犳硶闄愬埗a涓瓨鍦ㄧ殑key鐨勪釜鏁帮紝杩欑畝鍗曪紝鎴戜滑鍘诲垱寤虹被鍨嬪苟鍋氭柇瑷€鍗冲彲锛屽氨鍍忎笅杈硅繖鏍?/p>

interface Person{
    name:string;
    id:number;
}

const sp = {
    name:'spp'
} as Person

鐜板湪锛屾垜浠兂璁﹊d鑳藉鐏垫椿涓€鐐癸紝闄や簡number澶栵紝浼爏tring涔熷彲浠ワ紝鎵€浠ユ敼閫犲悗闀胯繖鏍?/p>

interface Person{
    name:string;
    id:number | string;
}

const sp = {
    name:'spp',
    id:410324
} as Person

姝ゆ椂褰撴垜浠幓璇诲彇id鍋氬鐞嗘椂锛岀敱浜嶵ypeScript鏃犳硶鍒ゆ柇褰撳墠鍒板簳鏄痭umber杩樻槸string绫诲瀷锛屽鑷村湪璋冪敤toFixed鏃跺氨浼氳鎺ㄦ柇鍑虹被鍨嬮敊璇簡

sp.id.toFixed()

浠ュ墠鎴戜滑闇€瑕佸埄鐢ㄦ嫭鍙风殑浼樺厛绾у啀涓€娆¤繘琛屾柇瑷€鏉ヨВ鍐宠繖涓棶棰?/p>

(sp as number).id.toFixed()

鐜板湪锛屾垜浠€氳繃satisfies鎿嶄綔绗﹀氨鍙互浠庢牴婧愪笂鏉滅粷璇ラ棶棰?/p>

const sp = {
    name:'spp',
    id:410324
} satisfies Person

sp.id.toFixed()

鎬荤粨

閫氳繃涓や釜绀轰緥鐨勮瑙o紝鎴戜滑鍙互鎬荤粨濡備笅锛?/p>

  • 鑳戒娇鐢╝s鐨勫湴鏂癸紝涔熷彲浠ヤ娇鐢╯atisfies

  • satisfies鍏奸【浜嗙被鍨嬪0鏄庡拰绫诲瀷鎺ㄥ

濡傛灉鏈枃瀵规偍鏈夌敤锛屽笇鏈涜兘寰楀埌鎮ㄧ殑鉂?/p>

璁㈤槄涓撴爮锛屾瘡鍛ㄦ洿鏂?-3绡囩被鍨嬩綋鎿嶏紝绛変綘鍝燄煒?/p>

github涓庡ソ鏂?/h2>
  • vue3鏍稿績鍘熺悊绮捐-涓撴爮-鎸佺画鏇存柊涓?..

  • TypeScript绫诲瀷浣撴搷-涓撴爮-姣忓懆鏇存柊

  • npm鍖呮彃浠跺寲鏂规璁捐涓庡疄鐜?/p>

  • 鍒╃敤cli-pkg瀹炵幇鑷姩鍙戝竷npm銆佸垱寤篻ithub release銆乬ithub tag

  • 鍚浣犺繕鍦ㄤ娇鐢ㄥ師鐢焞ocalStorage锛?/p>


https://www.xamrdz.com/database/6su1994421.html

相关文章: