0
0

More than 1 year has passed since last update.

TypeScript string | null →string の型変換 型アセーションを使う

Last updated at Posted at 2022-12-29

概要

typescript Nextjsの実装中 型合わせるのに苦労したので記事にします。

エラー箇所

requestBodyに入れるCustomer型の変数emailの型は string | null でありStateのemailと型と一致しており エラーになりません。
<Input value の型はstringなのでStateのemailと型が合わなく コンパイルエラーになります。
以下具体的なソース

sample.tsx
import {useState } from "react";
import { Customer } from "../../types/customer";
import { Button, CarouselItem, Form } from 'react-bootstrap';
export default function Sample(){
	const [email,setEmail] = useState<string | null>(null);
    const requestBody : Customer  ={
        email,		// Customer emailの型は string | nullなので コンパイルエラーにならない
    } ;
	return(
		<>
			<Form.Group className="mb-3" controlId="formBasicEmail">
				<Form.Label>Email address</Form.Label><br />
				<Form.Control 
					type="email" 
					placeholder="Enter email"  
					value  = {email} /><br /> //  valueの型は stringなのでコンパイルエラーになる
	</>
	)
}

customer.d.ts
export  type Customer = {
	email:string | null
	password:string | null
}

対処法

型アセーションを使う

import {useState } from "react";
import { Customer } from "../../types/customer";
import { Button, CarouselItem, Form } from 'react-bootstrap';
export default function Sample(){
	const [email,setEmail] = useState<string | null>(null);
    const requestBody : Customer  ={
        email,		// Customer emailの型は string | nullなので コンパイルエラーにならない
    } ;
	return(
		<>
			<Form.Group className="mb-3" controlId="formBasicEmail">
				<Form.Label>Email address</Form.Label><br />
				<Form.Control 
					type="email" 
					placeholder="Enter email"  
-					value  = {email} /><br />
+					value  = {email as string} /><br /> 
	</>
	)
}

参考

オライリー 「プログラミングTypeScript」 6.6.1 pp153

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