1
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 5 years have passed since last update.

【TypeScript】Genericに対して as const のようなことをする方法

Posted at

次のようなクラスがあったとします:

class X<T> {
	val: T;

	constructor(val: T) {
		this.val = val;
	}
}

このクラスを使ったコードを見てください:

const makeX = <T>(val: T): X<T> => new X(val);

const x = makeX('foo').val;

ここで、xの型はstringです。
場合によっては、これをstringではなく値そのものの型、'foo'にしたいときもあるかと思います。
TypeScriptではas constを使うと、値そのものの型を表現することができます。ただジェネリックに対してはas constを使えません。
どうするかというと、<T extends keyof any>のように書きます:

const makeX = <T extends keyof any>(val: T): X<T> => new X(val);

const x = makeX('foo').val;

こうすると、xの型は'foo'になります。めでたし


もっと良い方法があるよ!という方はお知らせください :pray:

1
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
1
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?