2017-06-06 59 views
2

如何定義通用類型基於參數或外部配置的React無狀態組件?Typescript具有通用參數/返回類型的React無狀態函數

實施例組分:

interface IProps<V> { 
    value: V; 
    doSomething: (val: V) => void; 
} 

const Comp: React.SFC<IProps<number>> = <T extends number>({ 
    value: T, 
    doSomething 
    }) => { 
return <div />; 
} 

以上示例將工作,而只用數字作爲值。

是可以做到的升級來實現類似:

const Comp: React.SFC<IProps<??>> = <?? extends string | number>({ 
    value, /* of type ?? */ 
    doSomething 
    }) => { 
return <div />; 
} 

這樣我們就可以決定,無論我們使用組件時需要數字或字符串。

所需的使用:

// This should setup generic type to string 
<Comp value="string" ... /> 

// Or number 
<Comp value={123} ... /> 

// Should be compilation error as we cannot use * on 'text' * 5 
<Comp value="text" doSomething={val => val * 5} /> 

編輯:應該做同樣的工作function做:

function Comp <T>({value, doSomething}: IProps<T>) { ... } 

SFC類型有定義:

interface SFC<P> { 
    (props: P & { children?: ReactNode }, context?: any): ReactElement<any>; 
    ... 
} 

回答

3

我能夠做到這一點TS 2.3。重點是對該組件的「內部」和「外部」使用2種類型。

interface IProps<V> { 
    value: V; 
    doSomething(val: V): void; 
} 

// type "inside" component 
function _Comp<T>(props: IProps<T>) { 
    return <div />; 
} 

// type for "outside" of component 
interface GenericsSFC extends React.SFC<any> { 
    <T>(props: IProps<T> & { children?: React.ReactNode }, context?: any): JSX.Element; 
} 

const Comp = _Comp as GenericsSFC; 

// dont type check: v is of type "hey" 
<Comp value={"hey"} doSomething={v => v - 1} />; 
+0

似乎工作,只是很好奇,如果沒有一些簡單的方法..也'GenericsSFC'需要其內部組件類型IProps,所以可能最好也保持GenericSFC裏面...... 可能是最好的可能只保留輸入函數,並且根本不使用SFC:o – Jurosh

相關問題