型アサーション
let name: any = "Tanaka"
let length = (name as string).length
// length = "foo"
// > error TS2322: Type 'string' is not assignable to type 'number'.
let name2: any = "Tanaka"
// JSXの記法と似ているため注意
let length2 = (<string>name2).length
constアサーション
let name = "Tanaka"
name = "Tatsuya"
let nickname = "Tatsuya" as const
nickname = "Tatsuya"
// nickname = "Tatsu"
// > error TS2322: Type '"Tatsu"' is not assignable to type '"Tatsuya"'.
let profile = {
name: "Tanaka",
height: 201
} as const
// プロパティがreadonlyとなる
// let profile: {
// readonly name: "Tanaka";
// readonly height: 201;
// }
// profile.name = "Tanaka"
// error TS2540: Cannot assign to 'name' because it is a read-only property.
// profile.height = 400
// error TS2540: Cannot assign to 'height' because it is a read-only property.