ITの隊長のブログ

ITの隊長のブログです。Rubyを使って仕事しています。最近も色々やっているお(^ω^ = ^ω^)

TypeScriptの雑なメモ

スポンサードリンク

ふぁ!?????ってなったことが多いのでとりあえず雑なメモを残す

ブルーベリー本から keyof

const mmC = {
    mm: 1,
    m: 1e3,
    km: 1e6
}

// OK
// function c(value: number, unit: keyof typeof mmC) {

// !???
// Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ mm: number; m: number; km: number; }'.
//  No index signature with a parameter of type 'string' was found on type '{ mm: number; m: number; km: number; }'.
function c(value: number, unit: string) {    
    const mv = value * mmC[unit]
    return {
        mm: mv,
        m: mv / 1e3,
        km: mv / 1e6
    }
}

console.log(c(5600, 'm'))

Genericsの練習とreact-hook-formの型エラーに苦しめられる殴りがき

import * as React from 'react';
import { useForm, UseFormWatch, WatchObserver, Path } from 'react-hook-form';

type FormData = {
  firstName: string;
  lastName: string;
};

type FormData2 = {
  age: number;
  phoneNumber: number;
}

type AO = {
  watch: UseFormWatch<FormData>
  watchFieldName: string
}

type A<T> = {
  watch: UseFormWatch<T>
  watchFieldName: string
}

export interface B extends A<FormData> {}
export interface C extends A<FormData2> {}

// export const useTestHook = ({
//   T,
//   watch,
//   watchFieldName
// }: A<T>) => {
function useTestHook<T,>({
  watch,
  watchFieldName
// }: A<T>) {
}: AO) {
// const useTestHook = <T,>({
//   watch,
//   watchFieldName
// }: A<T>) => {
// // }: B) => {
// // }: A<FormData>) => {
// // }: AO) => {
//   // OK
//   // const watchFieldName = 'lastName'
//   // console.log(watch(watchFieldName))

  // const watchFieldName: WatchObserver<FormData> = () => {};
  // console.log(watch(watchFieldName))
  console.log(watch(`${watchFieldName}` as const))
  console.log(watch('firstName'))
  return false
};

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm<FormData>();
  useTestHook<FormData>({ watch, watchFieldName: 'lastName' })
  // const { register2, handleSubmit2, watch2, errors2 } = useForm<FormData2>({
  //   defaultValues: {}
  // });

  return (
    <p>テスト</p>
  )
}

変化する型

同じじゃなくていいのか

import { UseFormWatch, FieldPath } from 'react-hook-form'

type AAA = {}
type ABCType = {
  watch: UseFormWatch<AAA>
  fieldName: keyof AAA  // よし!
}

const DatePickerForm = ({
  watch,
  fieldName,
}: ABCType) => {
  const { ... } =
    useA<AAA>({
      watch,
      fieldName,
    })
    // 省略
}


type A<T> = {
  watch: UseFormWatch<T>
  fieldName: FieldPath<T> // ↑←↑←!????
}

export const useA = <T>({
  watch,
  fieldName,
}: A<T>) => {
    // 省略 
}

react-hook-formの型はここだ

github.com

色々参考になった記事

qiita.com

zenn.dev

zenn.dev