[Note] TypeScript: 常用型別與寫法


Posted by urlun0404 on 2023-03-01

這篇是要不定期記錄開發中常遇到的型別,也會根據開發狀況陸續新增。


基本用法

這裡目前主要是參考這篇文章,並以React function component和props為例:

import React, {useState, suseRef} from 'react';

interface Props {
    children?: React.ReactNode;
    childrenElement?: JSX.Element;
    style?: React.CSSPropertiess;
    ref?: React.MutableRefObject;
    setInput: () => void
}

function App(){
    const [input, setInput] = useState('');

    return <Form setInput={setInput} />
}


function Form(props: Props){
    const inputRef = useRef(null);

    const handleChange = (event: React.ChangeEvent<HTMLInputElement>){
        // 這裡用 as 是為了避免偶爾會出現的編譯錯誤
        console.log( (event.target as HTMLInputElement).value );
    }

    return
        <form style={props.style}>
            <input type="text" ref={inputRef} onChange={handleChange}/>
            {props.children}
        </forms>
}



物件

物件的宣告方式有好幾種,個人認為最好的宣告方式就如同上面範例用 interface 清楚定義的 Props,不過也有其他定義物件的方式:

// 沒有明確指定key名稱
type AnyObject = { [key: string]: any };s

// 有限制key名稱
type Subject = "chinese" | "math" | "english" | ""
type SubjectObject = { [key in Subject]: number };



Immutable

type ConstantArray = ReadonlyArray<number>;
const scores = [50, 67, 80, 95] as const



References
Hold down the clap button and see something cool happen
Mutable and immutable useRef semantics with React & TypeScript
Declaration Reference @TypeScript Docs
宣告檔案 @TypeScript新手指南


#frontend #TypeScript #React







Related Posts

我的gulpfile.js要怎麼撰寫

我的gulpfile.js要怎麼撰寫

[11] 模組 Module

[11] 模組 Module

極簡複習:函式和模組的 Python 程式範例

極簡複習:函式和模組的 Python 程式範例


Comments