RN TS 实践

剩余参数

使用 & 来声明 props 的类型

1
2
3
4
5
6
7
8
const ListItem = ({
item,
...props
}: {
item: UIRecord;
} & ViewProps) => {
return <View ...props/>
}

children

1
children?: React.ReactNode | undefined;

字典的 key

1
2
3
const foo: {[key: string]: string} = {
'a': '123'
}

useRef

1
2
const allPageData = useRef<UIRecord[]>([]);
allPageData.current // 此时为 UIRecord[]
1
2
3
4
5
const listRef = useRef<FlatList|null>();
<FlatList
ref={(ref) => (listRef.current = ref)}
/>
listRef.current?.scrollToOffset(0)

type

普通 type

1
2
3
4
export type FooType = {
marked: boolean;
image?: string;
};

type 联合

1
2
3
4
export type FooType = {
marked: boolean;
image?: string;
} & ViewProps;

type 联合 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface OriginProps = {
name: string;
}

interface CustomProps extends OriginProps = {
age: number;
}

// Before
// export type FooType = {
// [key:string]: OriginProps;
// };

// After
export type FooType = {
[key:string]: CustomProps;
};

类型强转

1
const date: DateData = data.date as DateData;
  1. 剩余参数
  2. children
  3. 字典的 key
  4. useRef
  5. type
  6. 类型强转