关于useRef ts类型使用说明

180 阅读1分钟

关于strictNullCheckes

注:tsconfig.json文件compilerOptions.strictNullCheckes属性配置

{
  "compilerOptions": {
    "strictNullChecks": true,
  }
}

strictNullChecks官方说明

strictNullCheckes: false

null 会被视为 string 等类型的子类型。但正常情况下我们不会这么做,因此这里不做讨论。

strictNullCheckes: true

null视为与 string 等类型同级的一个类型(基础类型)。

关于useRef使用

注:这里只聊strictNullCheckstrue场景

useRef ts类型

interface RefObject<T> { 
    readonly current: T | null;
} 
interface MutableRefObject<T> {
    current: T;
}
function useRef<T>(initialValue: T): MutableRefObject<T>;
function useRef<T>(initialValue: T | null): RefObject<T>;

注:在 TypeScript 中,useRef 返回的RefObject可以是只读的或可变的,这取决于你的类型参数类型是否完全覆盖了初始值类型。

 DOM element ref

注:命中第二个函数重载定义(RefObject)

react DOM element ref

function Foo() {
  // - If possible, prefer as specific as possible. For example, HTMLDivElement
  //   is better than HTMLElement and way better than Element.
  // - Technical-wise, this returns RefObject<HTMLDivElement>
  const divRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Note that ref.current may be null. This is expected, because you may
    // conditionally render the ref-ed element, or you may forget to assign it
    if (!divRef.current) throw Error("divRef is not assigned");

    // Now divRef.current is sure to be HTMLDivElement
    doSomethingWith(divRef.current);
  });

  // Give the ref to an element so React can manage it for you
  return <div ref={divRef}>etc</div>;
}

image.png

Mutable value ref

注:命中第一个函数重载定义(MutableRefObject)

react Mutable value ref

function Foo() {
  // Technical-wise, this returns MutableRefObject<number | null>
  const intervalRef = useRef<number | null>(null);

  // You manage the ref yourself (that's why it's called MutableRefObject!)
  useEffect(() => {
    intervalRef.current = setInterval(...);
    return () => clearInterval(intervalRef.current);
  }, []);

  // The ref is not passed to any element's "ref" prop
  return <button onClick={/* clearInterval the ref */}>Cancel timer</button>;
}

image.png