You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Works with no types referenced or declared.// We only needed a single const assertion.functiongetShapes(){letresult=[{kind: "circle",radius: 100},{kind: "square",sideLength: 50}]asconst;returnresult;}for(constshapeofgetShapes()){// Narrows perfectly!// 可以大胆使用,不用担心kind会变化if(shape.kind==="circle"){console.log("Circle radius",shape.radius);}else{console.log("Square side length",shape.sideLength);}}
exportconstColors={red: "RED",blue: "BLUE",green: "GREEN",}asconst;// or use an 'export default'exportdefault{red: "RED",blue: "BLUE",green: "GREEN",}asconst;
注意事项
有一点需要注意的是,const断言只能立即应用于简单的字面表达。
// Error! A 'const' assertion can only be applied to a// to a string, number, boolean, array, or object literal.leta=(Math.random()<0.5 ? 0 : 1)asconst;letb=(60*60*1000)asconst;// Works!letc=Math.random()<0.5 ? (0asconst) : (1asconst);letd=3_600_000asconst;
const assertions
typescript3.4加入这个功能
它主要有以下特性:
string number boolean
字面量类型都不会被扩展;基于 const assertions 的强大功能,推断出来的值都是确定的,我们不需要显式地声明更多定义来进行类型推断(比如省略readonly,也不需要给result注明类型,会自动推断):
代替枚举类型
注意事项
参考文献
The text was updated successfully, but these errors were encountered: