react-native typescrpit使用時的數(shù)據(jù)定義及擴展運算符報錯問題記錄

Function Components

type AppProps = {
  message: string;
}; 

const App = ({ message }: AppProps) => <div>{message}</div>;

useState

const [count, setCount] = React.useState<number>(0);

// later...
setUser(1);

useReducer

onst initialState = { count: 0 };

type ACTIONTYPE =
  | { type: "increment"; payload: number }
  | { type: "decrement"; payload: string };

function reducer(state: typeof initialState, action: ACTIONTYPE) {
  switch (action.type) {
    case "increment":
      return { count: state.count + action.payload };
    case "decrement":
      return { count: state.count - Number(action.payload) };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = React.useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "decrement", payload: "5" })}>
        -
      </button>
      <button onClick={() => dispatch({ type: "increment", payload: 5 })}>
        +
      </button>
    </>
  );
}

useRef

const ref1 = useRef<HTMLElement>(null!);
const ref2 = useRef<HTMLElement>(null);
const ref3 = useRef<HTMLElement | null>(null);

Class Components

type MyProps = {
  // using `interface` is also ok
  message: string;
};
type MyState = {
  count: number; // like this
};
class App extends React.Component<MyProps, MyState> {
  state: MyState = {
    // optional second annotation for better type inference
    count: 0,
  };
  render() {
    return (
      <div>
        {this.props.message} {this.state.count}
      </div>
    );
  }
}

基本數(shù)據(jù)類型定義

type AppProps = {
  message: string;
  count: number;
  disabled: boolean;
  /** array of a type! */
  names: string[];
  /** string literals to specify exact string values, with a union type to join them together */
  status: "waiting" | "success";
  /** any object as long as you dont use its properties (NOT COMMON but useful as placeholder) */
  obj: object;
  obj2: {}; // almost the same as `object`, exactly the same as `Object`
  /** an object with any number of properties (PREFERRED) */
  obj3: {
    id: string;
    title: string;
  };
  /** array of objects! (common) */
  objArr: {
    id: string;
    title: string;
  }[];
  /** a dict object with any number of properties of the same type */
  dict1: {
    [key: string]: MyTypeHere;
  };
  dict2: Record<string, MyTypeHere>; // equivalent to dict1
  /** any function as long as you don't invoke it (not recommended) */
  onSomething: Function;
  /** function that doesn't take or return anything (VERY COMMON) */
  onClick: () => void;
  /** function with named prop (VERY COMMON) */
  onChange: (id: number) => void;
  /** alternative function type syntax that takes an event (VERY COMMON) */
  onClick(event: React.MouseEvent<HTMLButtonElement>): void;
  /** an optional prop (VERY COMMON!) */
  optional?: OptionalType;
};

React child 節(jié)點定義

interface AppProps {
  children1: JSX.Element; // bad, doesnt account for arrays
  children2: JSX.Element | JSX.Element[]; // meh, doesn't accept strings
  children3: React.ReactChildren; // despite the name, not at all an appropriate type; it is a utility
  children4: React.ReactChild[]; // better, accepts array children
  children: React.ReactNode; // best, accepts everything (see edge case below)
  functionChildren: (name: string) => React.ReactNode; // recommended function as a child render prop type
  style?: React.CSSProperties; // to pass through style props
  onChange?: React.FormEventHandler<HTMLInputElement>; // form events! the generic parameter is the type of event.target
  //  more info: https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring
  props: Props & React.ComponentPropsWithoutRef<"button">; // to impersonate all the props of a button element and explicitly not forwarding its ref
  props2: Props & React.ComponentPropsWithRef<MyButtonWithForwardRef>; // to impersonate all the props of MyButtonForwardedRef and explicitly forwarding its ref
}

使用中遇到的一些問題記錄

interface  user{
  name:string,
  id:string
}
interface Appprops{
  userList:user[]
}
//此時如果使用 ...擴展運算符展開userList,ts會報錯 說未實現(xiàn)Iterable接口
// eg  a= [...user] 
//改造user
interface  user{
  name:string,
  id:string已脓,
  [Symbol.iterator]() : Iterator,
}
//如果想通過 user['name'] 的方式獲取或設置user.name的值伸头,需要再次改造user接口
interface  user{
  name:string,
  id:string版述,
  [Symbol.iterator]() : Iterator,
  [key:string]:string
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市崖面,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖既们,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異正什,居然都是意外死亡啥纸,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門婴氮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來斯棒,“玉大人,你說我怎么就攤上這事主经∪倌海” “怎么了?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵罩驻,是天一觀的道長穗酥。 經(jīng)常有香客問我,道長惠遏,這世上最難降的妖魔是什么砾跃? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮节吮,結果婚禮上抽高,老公的妹妹穿的比我還像新娘。我一直安慰自己课锌,他們只是感情好厨内,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布祈秕。 她就那樣靜靜地躺著,像睡著了一般雏胃。 火紅的嫁衣襯著肌膚如雪请毛。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天瞭亮,我揣著相機與錄音方仿,去河邊找鬼。 笑死统翩,一個胖子當著我的面吹牛仙蚜,可吹牛的內容都是我干的。 我是一名探鬼主播厂汗,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼委粉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了娶桦?” 一聲冷哼從身側響起贾节,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎衷畦,沒想到半個月后栗涂,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡祈争,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年斤程,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片菩混。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡忿墅,死狀恐怖,靈堂內的尸體忽然破棺而出墨吓,到底是詐尸還是另有隱情球匕,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布帖烘,位于F島的核電站亮曹,受9級特大地震影響,放射性物質發(fā)生泄漏秘症。R本人自食惡果不足惜照卦,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望乡摹。 院中可真熱鬧役耕,春花似錦、人聲如沸聪廉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至框全,卻和暖如春察绷,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背津辩。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工拆撼, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人喘沿。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓闸度,卻偏偏與公主長得像,于是被迫代替她去往敵國和親蚜印。 傳聞我的和親對象是個殘疾皇子莺禁,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內容