0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【TypeScript】アサーション

Posted at

型アサーション

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.
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?